banner
Chenh

Chenh

SignalR

SignalR#

Description#

The purpose of SignalR is to establish a stable WebSocket connection, allowing the server to send messages to clients.

Usage#

Server#

Using the .net environment

  • Add the SignalR package to the project

  • Create a Hubs folder

  • Create the first SignalHub : Hub under the folder

  • Create our "signal" within this class

    using Microsoft.AspNetCore.SignalR;
    // ...
    // Signal can also carry parameters
    public async Task OrgnizationSignal(){
      await Clients.All.SendAsync("orgnizationChanged");
    }
    
  • Add SignalR service to the project

    // In Program.cs
    using CMS_miniAPI.Hubs;
    //...
    builder.services.AddSignalR();
    // Route mapping
    var app = builder.Build();
    app.MapHub<SignalHub>("/signalHub");
    
    app.Run();
    

Client (web)#

Here, we will use Vue-web client as an example

  • Install the SignalR package for the project

    npm install @microsoft/signalr

  • Import it in main.js

    import { HubConnectionBuild } from '@microsoft/signalr'

  • Establish the connection

    const connection = new HubConnectionBuild()
    	.withUrl('/signalhub')
    	.build();
    // Set up a listener
    connection.on('orgnizationChanged',()=>{
      console.log("message");
    })
    connection.start();
    

SignalR can be bundled on the web side and establish connections where needed.

Note#

  1. After adding the SignalR service in Program.cs, it should work normally.
  2. The purpose of the Hubs derived class is to store client-side SignalR method calls. The web client uses connection.invoke("name", {data}) to call the methods. The same applies to desktop applications, where the connection object's invoke method is used.
  3. To send messages directly from the server, you can use hubContext.Clients.All.SendAsync('name', data)
  4. hubContext stores the information of the current connection with the server, including the client list.
  5. Connection represents a SignalR communication channel established by the client.
  6. Another way to understand it is to refer to the methods in the Hub as SignalR server-side methods, and the client's connection.on('name', func) as SignalR client-side methods. Both sides can call each other. The server uses SendAsync to call the client, and the client uses invoke to call the server.

References#

  1. Web 实时通信,SignalR 真香,不用愁了 - Code 综艺圈 - 博客园 (cnblogs.com)
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.