一、分组说明
注:本示例
MvcContext.GetUser() 代码用于获取当前登录人id,根据实际项目自己封装就可以了。
1.添加连接到组 OnConnectedAsync
this.Groups.AddToGroupAsync(Context.ConnectionId, MvcContext.GetUser());
2.获取指定组的链接
this.Group(usernmae).SendAsync("hello", "本组成员好");
3.删除链接到组 OnDisconnectedAsync
this.Groups.RemoveFromGroupAsync(Context.ConnectionId, MvcContext.GetUser());
集线器定义:
/// <summary>
/// 用户操作连接
/// </summary>
public class UserHub : Hub
{
/// <summary>
/// 连接成功
/// </summary>
/// <returns></returns>
public override Task OnConnectedAsync()
{
////添加用户登录
//this.Context.User.AddIdentity();
////获取用户登录
//this.Clients.User()
this.Groups.AddToGroupAsync(Context.ConnectionId, MvcContext.GetUser());
return base.OnConnectedAsync();
}
/// <summary>
/// 连接失败
/// </summary>
public override Task OnDisconnectedAsync(Exception exception)
{
this.Groups.RemoveFromGroupAsync(Context.ConnectionId, MvcContext.GetUser());
return base.OnDisconnectedAsync(exception);
}
//通知除了本来接之外的其他链接
//通知除了本组之外的其他链接
public async Task ReceiveInfo(string content)
{
string id = this.Context.ConnectionId;
await this.Clients.AllExcept(id)
.SendAsync("hello", id + "已经上线," + content);
// this.Clients.GroupExcept()
}
}
二、后台通知本组连接
/// <summary>
/// 通知本组成员
/// </summary>
/// <returns></returns>
public IActionResult Two()
{
HubOperate _hub = new HubOperate();
string usernmae = MvcContext.GetUser();
//如果分组成员不存在,不会报错
_hub.GetUserHub().Clients.Group(usernmae).SendAsync("hello", "本组成员好");
return Content("执行完成");
}
三、前台通知除了本连接外其他所有
除了本组外其他所有。
<button id="btnOne"> 通知后台</button>
<script src="@aspnet/signalr/dist/browser/signalr.js"></script>
<script>
var connection = new signalR.HubConnectionBuilder()
.withUrl("/user")
.build();
connection.on('hello', function (data) {
console.info(data);
});
connection.start();
$('#btnOne').click(function () {
//客户端调用服务端
connection.invoke('receiveInfo', "abc").catch(function (err) {
console.error(err);
});
});
</script>
//通知除了本来接之外的其他链接
//通知除了本组之外的其他链接
public async Task ReceiveInfo(string content)
{
string id = this.Context.ConnectionId;
await this.Clients.AllExcept(id)
.SendAsync("hello", id + "已经上线," + content);
// this.Clients.GroupExcept()
}
更多:
Asp.Net Core SignalR JavaScript客户端重新连接