In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains the "ASP.NET Core real-time library SignalR how to use", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "ASP.NET Core real-time library SignalR how to use" it!
What is real time?
First explain the difference between the two in theory.
Most traditional web applications are like this: the client initiates a http request to the server, and the server returns the corresponding result. Like this:
In other words, in traditional web applications, the client initiates a request to the server.
What about real-time web applications? It does not need to initiate a request actively, and the server can actively push the information to the client.
If you take Chestnut, real-time chat tools and web games can all be regarded as real-time applications.
What is SignalR?
If you want to build a real-time application, you'd better use web socket. I wrote about the implementation of web socket a long time ago, but it's not comprehensive enough. I'll add another one here.
Let's talk about signalR, an open source real-time framework that can communicate in three ways (long polling, server sent events, web socket). It integrates the underlying technology well, so that we can focus on the business implementation without paying attention to the underlying technology implementation. A complete signalR includes both the client and the server, which supports net core/net framework and most clients, such as browsers and desktop applications.
Fall-down mechanism
In order to be compatible with different browsers (clients) and servers, signalR uses a fallback mechanism so that it can negotiate to use different underlying transport modes according to the situation. If the browser does not support web socket, it will be automatically downgraded to use sse, or long polling if not. Of course, you can also disable this mechanism and specify one of them.
Three communication methods long polling (long polling)
Long polling is when the client initiates a request to the server, and the server returns data directly. If there is no data, stay connected and wait until new data is returned. If the request remains unreturned for a period of time, it times out and the client initiates the request again.
The advantage of this approach is simplicity, but the disadvantage is that it consumes too many resources and basically does not consider it.
Server sent events (sse)
If sse is used, the server has the ability to push to the client, which is similar to the stream information and remains connected during the period.
The advantage of this method is still simple, and it also supports automatic reconnection, which is easier to use than long polling. The disadvantage is also obvious, do not support the old browser, but also can only send this message, and the browser also has a limit on the number of sse connections (6).
Web socket
Web socket allows both the client and the server to send messages to each other at the same time (that is, duplex communication) without restricting the type of information. Although browsers also have a limit on the number of connections (maybe 50), they are much better than sse. Theoretically, priority is given to use.
Get to the point.
Before you begin, you also need to understand the concepts of RPC and Hub.
RPC: the full name is Remote Procedure Call, which literally means remote service invocation, which can invoke remote services as if they were local methods. The front end can call the back-end method, and the back-end can also call the front-end method.
Hub: based on RPC, it accepts messages sent from the client, and is also responsible for sending messages from the server to the client. The client can call the method in Hub, and the server can call the method in the client through Hub.
All right, now that the concept is clear, let's go to the code.
Add the Hub class to the project:
Using Microsoft.AspNetCore.SignalR;using System.Threading.Tasks;namespace SignalRDemo.Server {public class SignalRHub: Hub {/ public override async Task OnConnectedAsync () {var cid = Context.ConnectionId; / / get the specified client var client = Clients.Client (cid) according to id when the customer connects successfully / send message await client.SendAsync ("Self", cid) to the specified user; / / send message await Clients.All.SendAsync ("AddMsg", $"{cid} joined chat room") to all users;}
In order to be accessible from the outside, we also need a controller. Declare in the controller to build a random one:
Using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.SignalR;using SignalRDemo.Server;using System.Threading.Tasks;namespace SignalRDemo.Controllers {public class HomeController: Controller {private readonly IHubContext _ countHub; public HomeController (IHubContext countHub) {_ countHub = countHub } / public async Task Send (string msg, string id) {await _ countHub.Clients.All.SendAsync ("AddMsg", $"{id}: {msg}");}
Then go to StartUp to set the endpoint:
Endpoints.MapHub ("/ hub")
When you are finished, configure the signalr client:
SetupConn = () = > {conn = new signalR.HubConnectionBuilder () .withURL ("/ hub") .build (); conn.on ("AddMsg", (obj) = > {$('# msgPanel') .append (`)
${obj}
`);}); conn.on ("Finished", () = > {conn.stop (); $('# msgPanel'). Text ('log outbound');}); conn.on ("Self", (obj) = > {$('# userId') .text (obj);}); conn.start () .catch (err = > console.log (err));}
Note that the path in withUrl is the endpoint you set up earlier.
Running effect:
Hub also supports group operations, such as:
/ / add the user to Group An await Groups.AddToGroupAsync (Context.ConnectionId, "GroupA"); / / kick the user out of Group An await Groups.RemoveFromGroupAsync (Context.ConnectionId, "GroupA"); / / broadcast the message await Clients.Group ("GroupA") .SendAsync ("AddMsg", "Group message") to all members of Group A. Thank you for your reading, the above is the content of "how to use ASP.NET Core real-time library SignalR". After the study of this article, I believe you have a deeper understanding of how to use ASP.NET Core real-time library SignalR, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.