SignalR在asp.net core下使用

消息即時推送服務,至關於一個微服務,
而客戶端的js也能夠當作是異步通訊的封裝,
他能夠訪問這個微服務定義的集線器hub
用一個最簡單的配置說明ajax

 

1.初始化json

nuget須要安裝 Microsoft.AspNetCore.SignalR
當前使用的版本是1.1
在startup文件裏app

 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
services.AddSignalR();
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConferenceService service, IBackgroundJobClient backgroundJobs)
{
app.UseSignalR(routes =>
            {
                routes.MapHub<DialogueHub>("/Hub"); 
 //這個定義的Hub就是虛擬出來的服務地址,咱們的具體服務文件也會放這個路徑
            });
}

2.js signalr封裝
官網的demo能夠直接使用,固然,根據本身的業務,要作些調整
創建個mysignalr.js文件異步

import n from 'namespace';
import * as sg from '../../libs/signal/dist/browser/signalr';
n.namespace('cj.signalR');
cj.signalR = sg;

這個是因爲我項目版本用了requirejs作管理,因此使用起來有點繞,不過配置好,仍是很穩定的
signalr的實例方法就有點變化了async


創建個myhub.js文件ide

import n from 'namespace';
n.namespace('cj.hub');

cj.hub = {
//構建頁面元素
init: function (options) {
var self = this;
this.setting = {};
$.extend(this.setting, options || {});
self.bindEvent();微服務

},
//綁定事件
bindEvent: function () {
var self = this;requirejs

var data = JSON.parse($('#djson').val());ui

if (typeof vm_dialogue === 'undefined') {
window.vm_dialogue = cj.ko_data(data, 'vm_dialogue');
} else {
cj.ko_dataRebind(data, vm_dialogue);
}this

console.info('dialogue', data);

var connection = new cj.signalR.HubConnectionBuilder().withUrl("/Hub").build();
//這個這樣實例化,好處固然是所有歸一到本身定義的cj命名空間了

//監聽這個ReceiveMessage方法,這個是後臺設置的第一個參數,這裏對應名字就好
//至於第二個參數後,有多個重載,如今支持10個object,
//例子暫時返回一個item對象
connection.on("ReceiveMessage", (item) => {
//var msg = item.Context.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

var userid = $('#huserid').val();
var dias = cj.tojs(vm_dialogue);
var dia = { Id: item.id, Context: item.context, Name: item.name, Logo: item.logo };
if (item.id === $('#huserid').val()) {
dia.IsOwner = true;
dia.IsVisable = false;
//判斷是否當前用戶發送
}
else {
dia.IsOwner = false;
dia.IsVisable = true;
}

dias.Items.push(dia);
cj.ko_dataRebind(dias, vm_dialogue);
if (typeof $('.ps--active-y')[0] !== 'undefined') {
$('.ps--active-y').scrollTop($('.ps--active-y')[0].scrollHeight);
}

});
//這裏加載必須打開,而後這裏的通信才生效
connection.start().then(function () {
//document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});

$('#msg_send').click(function (event) {
var userid = $('#huserid').val();
var message = $('#type_msg').val();
//這裏可看出異步ajax,把對應的內容發送到hub裏面
connection.invoke("SendMessageById", userid, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});

}
};

看下hub集線器的寫法

 public class DialogueHub : Microsoft.AspNetCore.SignalR.Hub
{
   /// <summary>
        /// 根據用戶ID發送消息
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageById(string userid, string message)
        {
//具體service經過DI注入獲得,
            var user = _service.UserBackById(Guid.Parse(userid));
            DialogueItem item = new DialogueItem();
            item.Context = message;
            item.Id = userid;
            item.Name = user.Name;
            item.Logo = user.Logo;
            await Clients.All.SendAsync("ReceiveMessage", item);
 //這個對應js的on方法,這個方法可支持10個obj參數

        }

 protected ICacheService _Cache;
        protected ILogger<DialogueHub> _logger;
        protected IConferenceService _service;
        public DialogueHub(ICacheService cache,
            ILogger<DialogueHub> logger,
            IConferenceService service
            )
        {
            _Cache = cache;
            _logger = logger;
            _service = service;
        }

}

這樣,整個signalR就配置好,可使用了。
其餘一些深刻點的使用,只列舉一下
Microsoft.AspNetCore.SignalR.Hub<IT>有個泛型接口方法,實現後能夠替換
SendAsync。
Clients除了All發送全部,還有個 Clients.User,能夠指定對應用戶等等

來個截圖看下效果

相關文章
相關標籤/搜索