LayIM.AspNetCore Middleware 開發日記(七)Asp.Net.Core.SignalR閃亮登場
前言
前幾篇介紹了整個中介軟體的構成,路由,基本配置等等.基本上沒有涉及到通訊部分。不過已經實現了融雲的通訊功能,由於是第三方的就不在單獨去寫。正好.NET Core SignalR已經出來好久了,於是乎趕緊對接上。可以先看一下之前的文章: ofollow,noindex" target="_blank">.Net Core SignalR初體驗 。
Hub設計
Hub我採用了 Hub<T>
,然後只定義了一個 Receive方法。
namespace LayIM.AspNetCore.IM.SignalR { public interface ILayIMClient { Task Receive(object message); } }
// Hub端程式碼 public Task SendMessage(string targetId, string message) { //這裡就可以呼叫 Receive方法 return Clients.Caller.Receive(message); }
那麼這裡我們要做的就是,先連線上伺服器在實現詳細業務。下面我們要做兩件事情:
Javascript
由於是將SignalR拆分到 LayIM.AspNetCore.IM.SignalR
專案中,所以註冊服務端程式碼做了小小封裝。在 SignalRServiceExtensions
檔案中:
/// <summary> /// 使用SignalR通訊 /// </summary> /// <param name="services"></param> /// <param name="setConfig"></param> public static IServiceCollection AddSignalR(this IServiceCollection services, Action<LayIMHubOptions> configure) { var options = new LayIMHubOptions(); configure?.Invoke(options); var signalRServerBuilder = services.AddSignalR(options.HubConfigure); //增加Redis配置 if (options.UseRedis) { signalRServerBuilder.AddRedis(options.RedisConfiguration, options.RedisConfigure); } //AddSignalR must be called before registering your custom SignalR services. services.AddSingleton<ILayIMAppBuilder, SignalRAppBuilder>(); //獲取使用者ID services.AddSingleton<IUserIdProvider, LayIMUserIdProvider>(); LayIMServiceLocator.SetServiceProvider(services.BuildServiceProvider()); return services; }
那麼在客戶端 Startup 呼叫的時候就可以這麼寫了:
//註冊LayIM的預設服務 services.AddLayIM(() => { return new MyUserFactory(); }).AddSignalR(options => { options.HubConfigure = hubOptions => { hubOptions.EnableDetailedErrors = true; hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(5); }; //使用Redis options.RedisConfiguration = "192.168.1.225:6379" }) .AddSqlServer(connectionString);
然後Configure方法中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { ....其他程式碼 //使用LayIM,自定義配置 app.UseLayIM(options => { options.ServerType = ServerType.SignalR; }); ....其他程式碼 }
到這裡可能大家有疑問,沒有看到新增 AddSignalR方法。由於是封裝了很多細節,所以,這一部分已經寫到了UselayIM程式碼中。
public class SignalRAppBuilder : ILayIMAppBuilder { public void Build(IApplicationBuilder builder) { builder.UseSignalR(route => { route.MapHub<LayIMHub>("/layimHub", connectionOptions => { }); }); } }
其實也就對應了上文中 services.AddSingleton<ILayIMAppBuilder, SignalRAppBuilder>();
這句程式碼。那麼到這裡呢,SignalR的服務該註冊的也註冊了,該新增的也添加了,下面就編寫(JS)客戶端程式碼。
SignalR Javascript客戶端
這裡我們根據官方文件裡寫就可以。連線部分核心程式碼:
let hubRoute = "layimHub"; let protocol = new signalR.JsonHubProtocol(); var options = {}; connection = new signalR.HubConnectionBuilder() .configureLogging(signalR.LogLevel.Trace) .withUrl(hubRoute, options) .withHubProtocol(protocol) .build(); //receive message connection.on('Receive', im.handle); connection.onclose(function (e) { if (e) { } log('連線已關閉' + e ? e : ''); }); connection.start() .then(function () { //連線成功 }) .catch(function (err) { log('伺服器連線失敗:' + err); });
layim.on('sendMessage', function (data) { //呼叫socket方法,傳送訊息 im.sendMsgWithQueue(data); });
呼叫服務端傳送方法:
if (im.connected) { this.invoke(connection, 'SendMessage', targetId, msg); }
invoke
方法
invoke: function () { if (!im.connected) { return; } var argsArray = Array.prototype.slice.call(arguments); connection.invoke.apply(connection, argsArray.slice(1)) .then(function (result) { if (result) { log(result); } }).catch(function (err) { log(err); }); },
可以看到,呼叫了服務端的 SendMessage
方法,那麼這裡就要回到 Hub
程式碼部分了。我們在 Hub
端新增方法 SendMessage
,然後定義好接收變數。如下:
public class LayIMMessage { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("avatar")] public string Avatar { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("content")] public string Content { get; set; } [JsonProperty("username")] public string UserName { get; set; } }
public Task SendMessage(string targetId, LayIMMessage message) { if (string.IsNullOrEmpty(targetId) || message == null) { return Task.CompletedTask; } var toClientMessage = LayIMToClientMessage<LayIMMessage>.Create(message, LayIMMessageType.ClientToClient); //如果訊息型別是群聊,呼叫OthersInGroup方法 if (message.Type == LayIMConst.TYPE_GROUP) { return Clients.OthersInGroup(targetId).Receive(toClientMessage); } else { //如果訊息型別是單聊,直接呼叫User //或者 Clients.Client([connectionId]) return Clients.User(targetId).Receive(toClientMessage); } }
這裡有兩個細節要注意,第一:使用者連線成功之後需要加入到 Group
,第二,自定義 UserIdProvider
。 那麼第一個,就是我們要在使用者連線成功之後呼叫一下加入群組的方法,同樣,使用者下線之後要移除掉。 IGroupManager
中定義瞭如下兩個方法:
namespace Microsoft.AspNetCore.SignalR { // // 摘要: //A manager abstraction for adding and removing connections from groups. public interface IGroupManager { Task AddToGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default(CancellationToken)); Task RemoveFromGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default(CancellationToken)); } }
至於自定義使用者ID,很簡單,我們實現介面 IUserIdProvider
即可。細心的同學可能在前文的程式碼中看到這一段了。為什麼要使用重寫呢?因為 SignalR
預設使用 ConnectionId
。而且每次重新整理頁面之後,它都是會變化的,那麼如果我們改成使用繫結使用者ID的話,對於直接定點推送,重新整理頁面是沒有問題的,直接根據 User
物件推送即可。下面演示一下:

群聊的圖就不貼了,一樣的。那麼至此SignalR的對接就結束了。是不是比Demo也難不了多少。
推送服務分離
到這裡呢,我們就可以融雲,SignalR自由切換了。具體細節可以檢視 LayIM.AspNetCore.Demo.RongCloud
, LayIM.AspNetCore.Demo.SignalR
兩個專案。
總結
給大家大體介紹了一下對接思路,其實有很多細節也沒有展示,畢竟貼的程式碼已經夠多了。如果小夥伴們有興趣,可以移步: 原始碼地址 ,今天就到這裡啦,再見,祝大家中秋快樂