一、program添加服务
scss
//添加SignalR服务
builder.Services.AddSignalR();
//映射通讯中心的请求路径
app.MapHub<ChatHub>("/Hubs");
二、工具类封装
csharp
//注意前端接受参数关键词:ReceivePublicMsg
public class ChatHub : Hub
{
public async Task SendMsg(string userId, string msg)
{
string sendMsg = $"服务端发起的消息,user={userId},msg={msg}";
//服务端推送给所有客户端
await Clients.All.SendAsync("ReceivePublicMsg", sendMsg);
await Clients.User(userId).SendAsync(msg);
//服务端推送给 除自已以外 的所有客户端
await Clients.Others.SendAsync("ReceivePublicMsg", sendMsg);
}
//客户端成功连接时,会触发此方法
public override Task OnConnectedAsync()
{
var id = Context.ConnectionId;
SendMsg(id, "测试消息");
return Task.CompletedTask;
}
//客户端断开连接时,会触发此方法
public override Task OnDisconnectedAsync(Exception? exception)
{
var id = Context.ConnectionId;
return Task.CompletedTask;
}
}