Asp.Net Core SignalR 分组使用示例

一、分组说明

注:本示例

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());

集线器定义:

    /// 
    /// 用户操作连接
    /// 
    public class UserHub : Hub
    {
        /// 
        /// 连接成功
        /// 
        /// 
        public override Task OnConnectedAsync()
        {
            ////添加用户登录
            //this.Context.User.AddIdentity();
            ////获取用户登录
            //this.Clients.User()
            this.Groups.AddToGroupAsync(Context.ConnectionId, MvcContext.GetUser());
            return base.OnConnectedAsync();
        }
        /// 
        /// 连接失败
        /// 
        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()
        }
    }

二、后台通知本组连接

/// 
/// 通知本组成员
/// 
/// 
public IActionResult Two()
{
    HubOperate _hub = new HubOperate();
    string usernmae = MvcContext.GetUser();
    //如果分组成员不存在,不会报错
    _hub.GetUserHub().Clients.Group(usernmae).SendAsync("hello", "本组成员好");
    return Content("执行完成");
}

三、前台通知除了本连接外其他所有

除了本组外其他所有。

    
    
    
//通知除了本来接之外的其他链接
//通知除了本组之外的其他链接
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客户端重新连接

Asp.Net Core SignalR获取集线器实例,从集线器外部发送消息

Asp.Net Core 2.0使用SignalR技术-入门

你可能感兴趣的:(Asp.net,SignalR,Asp.Net,Core,SignalR,分组使用示例)