preface

For B/S projects, the basic scenario is that the client initiates a request and the server returns the response result to end a connection. However, in many practical application scenarios, this simple request and response mode is very difficult, such as message notification, monitoring kanban information automatic refresh and other real-time communication scenarios, partners will certainly think of polling or WebSocket to solve the problem, but polling alone is a bit of resource consumption. The Websocket-only approach is not supported by some browsers or other clients, so many details will have to be worked out if you write from scratch. At this time SignalR should stand out, packaging is very powerful, direct use of the line.

The body of the

1. SignalR profile

SignalR is an open source library, cross-platform; It makes it easy for Web applications to communicate with other applications. Web servers can push content to corresponding clients in real time, and the information sent by clients can also be sent to other clients in real time.

SignalR provides a remote procedure call (RPC) method that allows clients to call server methods as well as client-side methods.

1.1 SignalR communication mode

SignalR supports real-time communication in the following ways:

  • WebSockets: A protocol for full-duplex communication over a single TCP connection, making it easier for the server to communicate with the browser, and for the server to proactively send messages.
  • Server-sent Events: SSE is similar to WebSocket in that it establishes a communication channel between the browser and the Server, and then the Server pushes information to the browser. WebSocket is two-way while SSE is one-way.
  • Long Polling(Long Polling) : The same principle as traditional Polling, but the server does not return a response every time. The server will only return a response when there is data or a time out, thus reducing the number of requests.

SignalR automatically selects the best communication method (good or not) within the capabilities of the server and client, or can be specified manually.

1.2 Application scenarios of SignalR

In fact, for real-time communication in Web mode, SignalR use to try, feel very powerful.

  • The server actively pushes information; For example, sending announcements;
  • Real-time display of monitoring or kanban data; For example, the monitoring system displays the data distributed to each client in real time;
  • Server and client interaction; Take the chat scene of the customer service system.

So much for the theory, and then a wave of examples.

2. Case demonstration

2.1 SignalR Server

Here I put SignalR server host in the WebAPI project, the actual need to host to the corresponding project (form application, background service), of course, can also create a separate project for it, but the code is basically the same.

  • Create a WebAPI project and import the corresponding Nuget package

  • Write your own SignalR Hub

    Hub is a class, but the method written in the client can be called remotely (principle later we read the source code together); It is also possible to use client-side methods remotely on the server, making real-time communication easy and convenient.

  • Register services and pipes in the startup. cs file

  • Business API preparation, push messages

    In fact, the above steps have completed SignalR server construction, the next need to add some business simulation, such as simulation of message push, convenient demonstration; Write the API as follows:

    The business to the server is done, and the client is written.

2.2 JS client

Js client uses Vue component, binding data is convenient; Put it in the WebApi project’s wwwroot directory, and share server startup with WebApi, so you don’t have to worry about cross-domain issues. If the front end is deployed separately, cross-domain needs to be configured in signalR-hosted projects. The specific steps are as follows:

  • Get signalR wrapped JS files out of the box

    npm init -y
    npm install @microsoft/signalr
    Copy the code

    NPM installs the package contents in the node_modules@microsoft\ Signalr \dist\browser folder in the current command directory. Create the wwwroot/signalr folder in the server project and copy the downloaded signalr.js file to the wwwroot\signalr folder.

    To use NPM, you need to install Node in advance, or download it directly. However, in real front-end projects, NPM is installed and used directly, there is no need to copy back and forth, this is just a demonstration.

  • Write index. HTML

    Put all static files in the WebAPI project’s wwwroot directory and share the server. In addition, Vue and asynchronous request are used, so it is necessary to introduce THE JS files of Vue and AXIos, which are introduced in the form of CDN address and not downloaded to the local, so they must be managed by themselves in real projects. As follows:

    The key script logic is as follows:

    Note: here we need to note that the client specified method name and received parameter resolution, is the form of camel.

  • Run to demonstrate the release effect, as follows:

    Is it very simple to achieve the push effect, there is no zha knock code, is not very fragrant. Are other client types supported? The answer is yes, any background service or form, the next step is to create a form client. By the way, Java clients are also supported, but feel free to use them. Net.

    Note: Some users cannot access the page when developing and running by themselves, because static page access is not supported by default in WebApi project, the corresponding middleware needs to be added as follows:

2.3 WinForm client

The layout is very simple, just put a text box in the form to display the message; Partners do not dislike ah, mainly reflects the process, beautify the interface partners themselves want to do it.

The core code is as follows:

The client is easily done, run to see the effect:

Get the server up and running (in this case, the WebApi project) and the Windows application running:

Implementation is not very powerful, now do not have to worry about the B/S mode, the server side active scene bar;

2.4 The client proactively reports data and displays it to other clients in real time

In the above scenario, the server takes the initiative to push data, but in many scenarios, the client takes the initiative to report data, which needs to be displayed to the data kanban or other client interfaces in real time. For example, some monitoring systems need to display equipment status in real time; Another example is a game-like scenario where one client changes and needs to be displayed to the other client in real time.

In the scenario where the client actively reports the information, the server needs to forward the information. Since no connection is established between the clients, only the server knows how many clients are connected. Therefore, a method needs to be added on the server for the client to call, as follows:

  • The server adds a method to the custom MyHub

  • This simulates data changes in the form client that are displayed in real time to other clients

    In the form client button click event directly call the server method, and pass the updated information, by the server call the client method and then forward to other clients.

  • The update method on the client side is only implemented on the Js client side. The same applies to other clients if necessary

  • Let’s see if it works

2.5 summary

The two scenarios listed above, server active push and client active push, can basically meet most real-time requirements. The communication flow chart is as follows:

  • The server pushes the message

    1. The Js client clicks the publish button to invoke the API interface;

    2. The interface sends the information to SignalR for processing.

    3. Obtain all the clients and pass the information to the clients by remotely calling the client methods. Finally, the information can be displayed in real time.

  • The client reports data

    1. Click the button on the window client to call the UpdateDataServer method on the server.

    2. After the server is invoked, all clients are obtained internally and the updateData method in the client is invoked. Finally, the information is displayed on the client.

Case source address: gitee.com/CodeZoe/dot…

conclusion

SignalR about the simple use of the first say so much, convenient and easy to use; Some key knowledge points will be shared later, such as sending messages to groups and users, adding authentication management, etc. Pay attention to “Code Variety Circle” and learn with me.