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#
- After adding the SignalR service in Program.cs, it should work normally.
- 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'sinvoke
method is used. - To send messages directly from the server, you can use
hubContext.Clients.All.SendAsync('name', data)
- hubContext stores the information of the current connection with the server, including the client list.
- Connection represents a SignalR communication channel established by the client.
- 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 usesSendAsync
to call the client, and the client usesinvoke
to call the server.