NetCore 下集成SignalR並進行分組處理

Tips:html

        一、注意跟普通版Net.MVC的前端處理方式不同,之前能夠connection.start()後直接done裏面再作邏輯處理,如今不行了前端

    建議作法是在具體的業務Hub裏重寫OnConnectedAsync事件,來爲當前鏈接ID作分組等處理web

        二、目前版本只支持了websocket協議,還不支持Comet長鏈接方式websocket

後臺代碼:socket

    public class MessengerHub : Hub
    {
        private readonly IHttpContextAccessor _accessor;
        public MessengerHub(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        //連上以後初始化Group
        public override async Task OnConnectedAsync()
        {
            var connectionId = Context.ConnectionId;
            var userInfo = _accessor.HttpContext.User.Identities.First(u => u.IsAuthenticated);
            await Task.Run(() =>
            {
                this.Groups.AddAsync(Context.ConnectionId, _accessor.HttpContext.User.Identity.Name);
            });
        }

        //給指定Group客戶端發送消息
        public async Task SendToMessage(string sendTo, string title, string content, int duration = 3000)
        {
            var connectionId = Context.ConnectionId;
            await Task.Run(() =>
            {
                sendTo.Split(',').ToList().ForEach(t =>
                {
                    this.Clients.Group(t).InvokeAsync("SendToMessage", "", title, content, duration);
                });
            });
        }
    }

前端代碼須要引入signalr-client.js,能夠在Bower包裏添加或者在Github上找下async

前端關鍵代碼:ide

//消息處理
let transportType = signalR.TransportType.WebSockets;
let http = new signalR.HttpConnection(`http://${document.location.host}/messengerHub`, { transport: transportType });
let connection = new signalR.HubConnection(http);
connection.start();

//setTimeout(connection.invoke('AddGroup'), 5000);
connection.on('SendToMessage', (sendTo, title, content, duration) => {
    layer.open({
        type: 1
        , time: duration
        , title: title
        , offset: 'rb'//具體配置參考:http://www.layui.com/doc/modules/layer.html#offset
        //, id: 'LAY_demo_rb' //防止重複彈出
        , content: '<div id="MessageTips">' + content + '</div>'
    });
});

注意這個地方註釋掉的connection.invoke('AddGroup'),這個地方不能在前臺JS裏面作分組初始化ui

前臺JS如今也不支持Done方法回調,因此寫在了後臺OnConnectedAsync方法裏this

客戶端發送方法跟之前的版本不同:connection.invoke('SendToMessage','Admin','標題','消息提示',2000);spa

相關文章
相關標籤/搜索