Outline
This series is divided into 2-3 articles.
- The first article introduces the preliminary knowledge and principles of SIGNALR.
- This article describes the use of SIGNALR in SIGNALR and ASP.
The content of this article:
- Introduction SIGNALR
- Using SIGNALR in ASP. NET Core
SignalR
SIGNALR is an open-source real-time framework for the. NET core/.net Framework. SIGNALR can use Web sockets, Server Sent Events, and Long polling as the underlying transport mode.
SIGNALR is built on these three technologies and is abstracted from them, which gives you a better focus on business issues than on the underlying transmission technology.
SIGNALR This framework sub-server and client, the server side support ASP. In addition to supporting JavaScript in the browser, the client also supports other types of clients, such as desktop applications.
Retreat mechanism
The three underlying transmission technologies used by SIGNALR are Web sockets, Server Sent Events, and Long Polling, respectively.
The web socket only supports a more modern browser, and the Web server is not too old.
The server Sent Events may be a bit better, but the same problem exists.
So SIGNALR uses a fallback mechanism, SIGNALR has the ability to negotiate the supported transport types.
Web socket is the best and most effective way to transfer, if the browser or Web server does not support it, it will downgrade the use of SSE, really do not use long Polling.
Once the connection is established, SIGNALR will begin sending keep alive messages to check if the connection is still working. If there is a problem, an exception is thrown.
Because SIGNALR is an abstraction of the upper layer of three modes of transmission, the use of SIGNALR is the same regardless of the underlying approach.
This fallback mechanism is used by SIGNALR to transmit and connect.
However, the fallback mechanism can also be disabled, using only one of the transmission modes.
Rpc
RPC (Remote Procedure call). The advantage is that you can invoke a remote service just as you would call a local method.
The SIGNALR uses the RPC paradigm to communicate between the client and server side.
SIGNALR uses the underlying transport to allow the server to invoke the client's methods, and vice versa, these methods can take parameters, parameters can also be complex objects, SIGNALR is responsible for serialization and deserialization.
Hub
The hub is a component of SIGNALR, which runs in the ASP. NET Core application. So it's a class on the server side.
The hub uses RPC to accept messages from clients, and it can send messages to clients. So it's a hub for communication.
in ASP. NET core, the Hub class you create needs to inherit from the base class hub.
Inside the Hub class, we can invoke the methods on all clients. The same client can also invoke the method in the Hub class.
This hub+rpc approach is well suited for real-time scenarios.
It was previously said that when a method call can pass complex parameters, SIGNALR can serialize and deserialize parameters. The format in which these parameters are serialized is called the Hub protocol, so the Hub protocol is a format for serialization and deserialization.
The default protocol for the hub protocol is JSON, and another protocol is supported by Messagepack. Messagepack is a binary format that is more compact than JSON and is simpler and faster to handle because it is binary.
In addition, SIGNALR can also extend the use of other protocols.
Horizontal Scaling
As the system runs, sometimes you may need to scale out. Is that the application is running on multiple servers.
The load balancer then ensures that each incoming request is logically assigned to a server that may be different.
When using a Web socket, there is no problem, because once the web socket connection is established, as if the browser and that server opened a tunnel, the server will not switch.
However, if you use long Polling, there may be a problem, because with long Polling, each send message is a different request, and each request may reach a different server. Different servers may not be aware of the contents of the previous server communication, which can cause problems.
For this problem, we need to use Sticky Sessions (sticky session).
Sticky Sessions seems to have a lot of implementations in the way, but the main is the following to introduce this way.
As part of the response to the first request, the load balancer sets a cookie in the browser to indicate that the server was used. In subsequent requests, the load balancer reads the cookie and then assigns the request to the same server.
Using SIGNALR to build projects in ASP.
Create an ASP. NET core project using an empty template.
Establish a Countservice:
Build a Counthub that inherits from the hub:
Configure SIGNALR
Register SIGNALR in Startup:
You can use lambda expressions in the addsignalr () method to make some configuration, if necessary.
Then use the SIGNALR in the pipeline and use the app. USESIGNALR ():
Here I have built a hub called Counthub.
The parameter type of the method is action, and then the hub's route is configured here.
Using the Hub First build a controller, and inject ihubcontext<counthub>:
Next we can use the Ihubcontext<counthub> object to communicate with the client in real time.
Here we create a post action, the client clicks the button and comes to this action, where we use the hub to send a message to all the clients:
Here, I call the SomeFunc method on all clients, and the parameter is an object.
But with this ihubcontext
Context From the hub's context property, we can get the user's information.
We're in the Counthub. A method of the parent class Onconnectedasync ():
If a new connection is established, this method will be executed.
In the Hub class, we have access to the context property. From the context property, we can get a commonly used property called ConnectionID. This ConnectionID is the unique identity of this client connected to the hub.
Using ConnectionID, we can get this client and call its method, in the Clients.client (ConnectionID). xxx.
The clients property of the hub represents the client, it has several methods to select the client, and the client (ConnectionID) just found it using ConnectionID. and Allexcept (ConnectionID) is all clients except this ConnectionID client. See the documentation for more methods.
SIGNALR also has the concept of group grouping, and the operation is simple, here is the Hub's Groups property. When you add the first ConnectionID to a group name, the grouping is created. When the last client in the group is removed, the grouping is deleted. You can use Clients.group ("group name") to invoke methods within a group of clients.
Authorization and verification The SIGNALR uses an ASP. NET core configured authorization and authentication system.
The usage is similar to controller:
To get the User object, you need to use Context.User, whose type is claimsprinciple:
Client The client needs to install SIGNALR this library. You can use NPM to install @aspnet/signalr
But actually only need to signalr.js a file.
The client code is as follows:
Click the button to execute the controller's post method first, Post returns accepted (1), so the ID is 1.
Use the hubconnectionbuilder of the Singalr object to build the connection. Using the returned Connection object, we can use its on method to handle the response of the server-side method call. The parameters of the response method can be simple types or complex objects.
Use connection. start () to open the connection, use catch () to catch the exception, use connection. Stop () closes the connection.
Run it first to see the effect:
You can see that all of the client's methods are called using Clients.all.
As soon as we opened the page, we tried to make a connection, and from F12 we could see a request called negotiate was sent:
The body of this request is as follows:
You can see that the client has selected a ConnectionID, which also has a browser-supported transmission.
Response from the server:
The response also contains the ConnectionID, as well as the mode of transport supported by the server. Here are three kinds of support. Since I did not specify the transfer mode, SIGNALR chose the best way: WebSocket.
And after I click the button, the WEB socket connection is initialized:
If you need to specify the transfer mode manually, specify the transport method in the second parameter of the Withurl () method:
Other types of clients . NET clients can install Microsoft.AspNetCore.SignalR.Client This package to support SignalR.
For specific usage, please check the official documentation, syntax and JS.
Messagepack protocol Need to install Microsoft.AspNetCore.SignalR.Protocols.MessagePack.
You can then use the addmessagepackprotocol () method in Startup:
In this case, the server side supports both JSON and messagepack.
Other than that. NET client also needs to install this Messagepack package.
And the JS client needs to install @aspnet/signalr-protocol-msgpack.
Scale-out Scale-out Redis is available and requires installation of Microsoft.AspNetCore.SignalR.Redis. This bag.
Then in the startup configuration:
This has not been tried, please read the official documents.
SIGNALR introduced these ....