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技術-入門

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章