Asp. Net Signalr message push test instance in WinForm, winformsignalr
Asp. Net Signalr message push test instance in WinForm
Signalr is a beginner. You only need to learn more about it. SignalR provides a simple API for creating Remote Procedure Call (RPC) from a server. NET code to a server that calls JavaScript Functions in a client browser (and other client platforms) to a client ). SignalR also includes APIs for connection management (such as connection and disconnection events) and group connection.
The above descriptions are all put forward in the official documentation. The main requirements of my test project are as follows:
1. Create a SignalR service for broadcasting information in real time for the client. 2. Create a client that only pushes messages to the server, but does not receive broadcast information from the server. 3. WinFrom program or ASP. net wbe client program, used to receive and display received information.
Basic flowchart:
Wait
With a clear requirement, open VS and start it directly.
1. Create a SignalR server first
Only three steps are required to create a SignalR broadcast service.
Step 1: Create a project (WF or console) and download the SignalR dynamic library from NuGet.
Step 2: create a HUB class for the client to access the connection
/// [HubName ("MyHub"), Authorize] public class MyHub: Hub {public List <string> UserIdList1 {get ;}= new List <string> (); /// <summary> /// information broadcast /// </summary> /// <param name = "identify"> unique iot identifier </param> // <param name = "model"> Data model </param> [HubMethodName ("Send")] public void Send (string identify, IOTModel model) {Clients. all. addMessage (identify, model );} /// <summary> /// Error Log broadcast /// </summary> /// <param name = "identify"> Unique Identifier </param> /// <param name = "errMessage"> error message </param> [HubMethodName ("ErrSend")] public void Send (string identify, string errMessage) {Clients. all. addMessage (identify, errMessage);} // <summary> // return real-time data to the client that is connected for the first time, for display /// </summary> /// <param name = "identify"> </param> /// <param name = "list"> </param> [hubMethodName ("initSend")] public void Send (string identify, List <IOTModel> list) {Clients. all. initData (identify, list);} public override Task OnConnected () {UserIdList1.Add (Context. connectionId); // the last record in MongoDB needs to be returned for the first connection for the client to display Send ("IotList", ProdMongoDB. getLastData (); return base. onConnected ();} public override Task OnDisconnected (bool stopCalled) {UserIdList1.Remove (Context. connectionId); return base. onDisconnected (stopCalled);} public override Task OnReconnected () {UserIdList1.Add (Context. connectionId); return base. onReconnected ();}}
Step 3: Enable the Signalr Service asynchronously
Before starting the service, you must set the IP address and port of the service.
private IDisposable SignalR { get; set; } private string ServerURI = "http://" + ConfigurationManager.AppSettings["signalrAdress"]; private async void RunServer() { await Task.Run(() => StartServer()); } private void StartServer() { try { SignalR = WebApp.Start(ServerURI); } catch (TargetInvocationException) { SignalR.Dispose(); Console.WriteLine("Server failed to start. A server is already running on " + ServerURI); return; } }
2. Create a client (WinForm or console program) to send information to the server.
This client is only responsible for sending information to the server and does not receive broadcast information from the server. The creation process is as follows:
Step 1: Create a WF or console program and add a dynamic library
Step 2: create a connection object and configure the service address
// Define the proxy. private static IHubProxy HubProxy {get; set;} private static readonly string ServerUrl = ConfigurationManager. deleetask[ "signalrServer"]; // private static string _ serverUrl = ""; // defines a Connection object public static HubConnection Connection {get; set ;}
Step 3: asynchronously connect to the server
// Asynchronous Connection server private async void ConnectAsync () {Connection = new HubConnection (ServerURI); Connection. closed + = Connection_Closed; HubProxy = Connection. createHubProxy ("MyHub"); try {await Connection. start ();} catch (HttpRequestException) {_ logger. error ("Unable to connect to server: Start server before connecting clients. "); return ;}}
Part 4: Send real-time information to the server
HubProxy.Invoke("Send", "aaa", message);
The Send method called in the sending information is defined in the HUB class of the server, and is defined and used according to actual needs.
3. Create a WinForm client program to receive broadcast information from the server.
The winform client defines that the connection to the server is the same as that in the above 2. The difference is that this client only receives information and does not send information.
Skip the Connection Service Section
Monitors server information in real time
Connection = new HubConnection (_ serverUrl); Connection. closed + = Connection_Closed; HubProxy = Connection. createHubProxy ("MyHub"); HubProxy. on <string, IOTModel> ("AddMessage", RecvMsg); // receives real-time information HubProxy. on <string, string> ("addMessage", RecvMsg); // receives the error log HubProxy. on <string, List <IOTModel> ("initData", RecvMsg); // initialize the monitoring data
Create a RecvMsg Method for parsing and processing the displayed data
Private static void RecvMsg (string identifiy, string errMessage) {if (identifiy! = "ErrorInfo") return; ErrorList. add ("error message:" + errMessage + ", receiving time:" + DateTime. now); // Add it to richBox in real time if (ErrorBox. invokeRequired) {ErrorBox. invoke (Action) () => ErrorBox. appendText ("error message:" + errMessage + ", receiving time:" + DateTime. now + "\ r \ n"); return;} ErrorBox. appendText ("error message:" + errMessage + ", receiving time:" + DateTime. now + "\ r \ n ");}
4. Create an aps.net Web client to receive server broadcast information like WinForm.
Creating a web Client is also simple, as follows:
Step 1: Create an asp.net web application and obtain a dynamic package
The required js files are as follows.
Step 2: Create an html page and write the script code to receive broadcast information.
<script src="Scripts/jquery-3.0.0.js"></script> <script src="Scripts/jquery.signalR-2.2.2.js"></script> <script src="http://172.30.16.165:805/signalr/hubs"></script>
$ (Function () {// configure the address of the hub server $. connection. hub. url = "http: // localhost: 888/signalr"; // declare a hub proxy. Here, MyHub is the Hub name configured on the server. var proxy =$. connection. myHub; // defines the function to receive service broadcasts. addMessage is the method proxy received by the client defined by the server. client. addMessage = function (name, message) {// parse the received data if (name = "FYIot ") {var html = "<tr> <td>" + message. configCode + "</td>"; html + = "<td>" + message. configValue + "</td>"; html + = "<td>" + moment (message. saveDate ). format ("YYYY-MM-DD HH: mm: ss") + "</td> </tr>"; $ ("# sigBody "). append (html) ;}// Connection Service $. connection. hub. start (). done (); $ ("# tableDiv "). slimScroll ({height: 500 });});
<Div style = "text-align: center"> Conclusion: the above steps can be used to build a communication instance between the client and the server based on Signalr. The powerful signalr still needs to be learned and explored continuously. Looking forward to throwing bricks.