天天看點

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

集線器定義:

/// <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用戶端重新連接配接

Asp.Net Core SignalR擷取集線器執行個體,從集線器外部發送消息

Asp.Net Core 2.0使用SignalR技術-入門