Asp.Net SignalR已经出来很久了,但是一直没有静下心来好好看看。昨天花了几个小时的时间看了下。首先借鉴了官方文档,如何搭建一个SignalR的Demo。
参考文章:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/signalr?view=aspnetcore-2.1&tabs=visual-studio
SignalR地址:https://github.com/aspnet/SignalR
所以为了快速搭建和体验.Net Core版本的SignalR,我选择了下载官方的Demo和参考官方给的教程。所以具体的搭建过程我就不再本文中写了。
体验效果官网给出的DEMO运行如下图:
点击connect,查看一下network。可以发现,它在当前浏览器支持三种方式。
而且和.NET Framework版本不同的是,新版SignalR中的Hub类型也是蛮丰富的。Demo中给出了 普通Hub,DynamicHub,Hub<T> 三种类型。我们去看看其中的区别吧。
普通Hub
查看定义,可以看到普通Hub中的Clients类型是 IHubCallerClients
namespace Microsoft.AspNetCore.SignalR { // // 摘要: // A base class for a SignalR hub. public abstract class Hub : IDisposable { protected Hub(); // // 摘要: // Gets or sets an object that can be used to invoke methods on the clients connected // to this hub. public IHubCallerClients Clients { get; set; } // // 摘要: // Gets or sets the hub caller context. public HubCallerContext Context { get; set; } // // 摘要: // Gets or sets the group manager. public IGroupManager Groups { get; set; } // public void Dispose(); // // 摘要: // Called when a new connection is established with the hub. // // 返回结果: // A System.Threading.Tasks.Task that represents the asynchronous connect. public virtual Task OnConnectedAsync(); // // 摘要: // Called when a connection with the hub is terminated. // // 返回结果: // A System.Threading.Tasks.Task that represents the asynchronous disconnect. public virtual Task OnDisconnectedAsync(Exception exception); // // 摘要: // Releases all resources currently used by this Microsoft.AspNetCore.SignalR.Hub // instance. // // 参数: // disposing: // true if this method is being invoked by the Microsoft.AspNetCore.SignalR.Hub.Dispose // method, otherwise false. protected virtual void Dispose(bool disposing); } }