SignalR for Core 是 SignalR 的浴火重生版,允许你在 Core 中实现实时通讯,这里的实时
意味着双方都能快速的感知对方发来的消息,比如:一旦 server 端有需要推送的内容将会直接 push 到 client,这和原始的 http 单向请求有着本质的区别。
值得注意的是, Core 版的 SingalR 移除了老版的诸多功能,比如:
自动重连机制
消息处理机制
单连接多hub
不过无需担心,新版的 SingalR 在健壮性和易用性上做了非常大的改进,总的来说,新版本已不兼容老版本,而且新的 SingalR 客户端采用的是 TypeScript 。
安装 SingalR
要想使用SingalR
,需要通过 nuget 引用Microsoft.AspNetCore.SignalR
包,可以通过 Visual Studio 的NuGet package manager
可视化界面安装 或者 通过NuGet package manager
命令行工具输入以下命令:
Install-PackageMicrosoft.AspNetCore.SignalR
使用 SignalR broadcast
现在我们一起实现一下如何在 Core 应用程序中使用 SignalR 的广播消息,那怎么做呢?创建一个自定义的MessageHub
类并继承类库中的Hub
基类,在 MessageHub 中定义一个 SendMessage 方法,该方法用于向所有已连接的客户端发送消息,如下代码所示:
publicclassMessageHub:Hub{publicasyncTaskSendMessage(stringuser,stringmessage){awaitClients.All.SendAsync("ReceiveMessage",user,message);}}
配置 SignalR
要想在 Core 中使用 SignalR,只需在Startup.ConfigureServices()
中调用扩展方法AddSignalR()
将其注入到 ServiceCollection 中即可,如下代码所示:
publicclassStartup{publicStartup(IConfigurationconfiguration){Configuration=configuration;}publicIConfigurationConfiguration{get;}//Thismethodgetscalledbytheruntime.Usethismethodtoaddservicestothecontainer.publicvoidConfigureServices(IServiceCollectionservices){services.AddSignalR();services.AddControllersWithViews();}}
为了能够启用 MessageHub,需要在Startup.Configure
方法中添加如下代码:
publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){app.UseEndpoints(endpoints=>{endpoints.MapControllerRoute(name:"default",pattern:"{controller=Home}/{action=Index}/{id?}");endpoints.MapHub<MessageHub>("/messagehub");});}
创建 SignalR client
SignalR 的 client 是任意的,意味着它可以是 html, windowform, wpf,console 甚至是 java 程序,它们都可以消费 server 端发来的消息,接下来准备创建一个 Console 程序尝试一下,那如何做呢?需要在 client 端引用Microsoft.AspNetCore.SignalR.Client
和System.Text.Encodings.Web
两个nuget包,如下代码所示:
classProgram{staticasyncTaskMain(string[]args){HubConnectionconnection=newHubConnectionBuilder().WithUrl("http://localhost:55215/messagehub").Build();connection.On<string,string>("ReceiveMessage",(user,message)=>{varnewMessage=$"{user}:{message}";Console.WriteLine(newMessage);});awaitconnection.StartAsync();awaitconnection.InvokeAsync("SendMessage","jack","hello,world");Console.ReadLine();}}
接下来就可以调试一下,分别启动 server 和 client 端,如下图所示:
server
client
译文链接:/article/3267165/how-to-use-signalr-in-aspnet-core.html