当前位置:网站首页>[signalr complete series] Realization of signalr real-time communication in net core

[signalr complete series] Realization of signalr real-time communication in net core

2022-06-09 11:44:00 [fun programming] NET

  WeChat official account : Fun programming ACE
Pay attention to learn more about .NET Daily actual combat development skills , For source code Please leave a message at the backstage of official account   Source code
[ If you think this official account is helpful to you , Welcome to your attention ]

Previous review

【SignalR Complete series 】 It's in .NetCore To realize WebSocket Duplex communication

【SignalR Complete series 】 It's in .Net Core To realize Server-Send Events Message push

【SignalR Complete series 】 It's in .Net Core Long polling in


SignalR Basic use of


Link to the original text :【SignalR Complete series 】 It's in .Net6 Zhongshi SignalR signal communication


brief introduction

1.SignalR Is a Microsoft open source library , It is used for the mutual communication between the client and the server .
2. As previously outlined WebSocket、SSE、 Long polling, etc ,SignalR All support , In addition, it can automatically select the best communication mode .
3. As for the purpose , It is mainly used in scenarios with high real-time requirements , such as : Chat 、 Kanban 、 Announcement, etc

Server implementation

newly build .net6 project

edit

1. Inject SignalR Services needed

1//  Inject SignalR Services needed 
2builder.Services.AddSignalR();

2. Inject SignalR Services needed

1//  Open static file    Write client code to wwwroot in    Prevent cross domain 
2app.UseStaticFiles();

3. Turn on SignalR Routing nodes for

1//  Turn on the routing node   Used to map Signalr Request path   
2// /custom  For custom paths   
3// CustomHub  by Hub  type 
4app.MapHub<CustomHub>("/custom");
5//  It also supports grouping requests , The next part is about ,,,,

3. Customize a Hub type Inherit Hub

1// CustomHub:Hub  Inherit  Hub
2public class CustomHub:Hub<ClientData>{}

4. rewrite Hub in Connection and closing methods

 1        /// <summary>
 2        ///  Rewrite the link hook 
 3        /// </summary>
 4        /// <returns></returns>
 5        public override Task OnConnectedAsync()
 6        {
 7            return base.OnConnectedAsync();
 8        }
 9
10        public override Task OnDisconnectedAsync(Exception? exception)
11        {
12            return base.OnDisconnectedAsync(exception);
13        }

5. The logging middleware is introduced into the constructor

1//  Introducing logs   Convenient console output 
2private readonly ILogger<CustomHub> _logger;
3
4public CustomHub(ILogger<CustomHub> logger)
5{
6   this._logger = logger;
7}

6. Write the communication method with the client

 1        /// <summary>
 2        ///  Establish communication 
 3        /// </summary>
 4        /// <param name="data"></param>
 5        public void BeginSendData(TransData data)
 6        {
 7            _logger.LogInformation(" Receive data {0},{1}",data.id,data.message);
 8        }
 9
10        /// <summary>
11        ///  Single client call   signal communication 
12        ///  Notification only   The client to call   Other linked clients do not generate communication 
13        /// </summary>
14        /// <returns></returns>
15        public Task SingleClientCaller()
16        {
17            _logger.LogInformation(" Individual client calls ");
18            return Clients.Caller.ClientHook(new (111,"111  Client calls "));
19        }
20
21        /// <summary>
22        ///  All clients establish communication 
23        ///  All clients can be notified 
24        /// </summary>
25        /// <returns></returns>
26        public Task AllClientResponse()
27        {
28            _logger.LogInformation(" Notify all clients ");
29
30            return Clients.All.ClientHook(new(Guid.NewGuid()," Notify all clients "));
31        }
32
33        /// <summary>
34        ///  Designated call   
35        /// </summary>
36        /// <returns></returns>
37        [HubMethodName("invoke")]
38        public TransData IvoData()
39        {
40            return new TransData(666," return invoke data");
41        }

Client implementation

1. quote js library

edit

2. Write a call script

1//  initialization   route :/custom  Captured by the routing node 
2let connection = new signalR.HubConnectionBuilder()
3        .withUrl("/custom")
4        .build();
1//  Start connecting   Call the background  BeginSendData  Method   After success, the two sides will exchange data 
2        connection.start().then(() => {
3        console.log(" Start linking ")
4        let id = parseInt(Math.random()*100);
5        connection.send('BeginSendData', {id: id, message: " The link succeeded "})
6    });
 1    //  call  SingleClientCaller  This method 
 2    const selfCall = () => connection.send('SingleClientCaller')
 3
 4    //  call AllClientResponse This method 
 5    const all = () => connection.send('AllClientResponse')
 6
 7    //  Trigger the background controller 
 8    const triggerFetch = () => fetch('/SendData')
 9
10    // call signalR hub function from client
11    const withReturn = () => connection.invoke('invoke')
12        .then(data => console.log('ivo data', data))
1 //  The default trigger is in the background 
2    connection.on("ClientHook", data => console.log(' The client triggered successfully ', data));
3
4    //  After the background specified method is triggered 
5    connection.on("client_recive", data => console.log(' The background trigger is successful ', data));

The above is SignalR The basic method to realize the communication between client and server , The next article will demonstrate packet communication

More wonderful contents are available in the official account :


原网站

版权声明
本文为[[fun programming] NET]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091053267171.html