如何在 ASP.Net Core 中使用 SignalR

SignalR for ASP.Net Core 是 SignalR 的浴火重生版,允许你在 ASP.Net Core 中实现实时通讯,这里的 实时 意味着双方都能快速的感知对方发来的消息,比如:一旦 server 端有需要推送的内容将会直接 push 到 client,这和原始的 http 单向请求有着本质的区别。

值得注意的是, ASP.Net Core 版的 SingalR 移除了老版的诸多功能,比如:

  • 自动重连机制
  • 消息处理机制
  • 单连接多hub

不过无需担心,新版的 SingalR 在健壮性和易用性上做了非常大的改进,总的来说,新版本已不兼容老版本,而且新的 SingalR 客户端采用的是 TypeScript 。

安装 SingalR

要想使用 SingalR,需要通过 nuget 引用 Microsoft.AspNetCore.SignalR 包,可以通过 Visual Studio 2019 的 NuGet package manager 可视化界面安装 或者 通过 NuGet package manager 命令行工具输入以下命令:


Install-Package Microsoft.AspNetCore.SignalR

使用 SignalR broadcast

现在我们一起实现一下如何在 ASP.Net Core 应用程序中使用 SignalR 的广播消息,那怎么做呢?创建一个自定义的 MessageHub 类并继承类库中的 Hub 基类,在 MessageHub 中定义一个 SendMessage 方法,该方法用于向所有已连接的客户端发送消息,如下代码所示:


    public class MessageHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }

配置 SignalR

要想在 ASP.Net Core 中使用 SignalR,只需在 Startup.ConfigureServices() 中调用扩展方法 AddSignalR() 将其注入到 ServiceCollection 中即可,如下代码所示:


    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR();
            services.AddControllersWithViews();
        }
    }

为了能够启用 MessageHub,需要在 Startup.Configure 方法中添加如下代码:


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            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.ClientSystem.Text.Encodings.Web 两个nuget包,如下代码所示:


    class Program
    {
        static async Task Main(string[] args)
        {
            HubConnection connection = new HubConnectionBuilder()
                .WithUrl("http://localhost:55215/messagehub")
                .Build();

            connection.On<stringstring>("ReceiveMessage", (user, message) =>
            {
                var newMessage = $"{user}{message}";

                Console.WriteLine(newMessage);
            });

            await connection.StartAsync();

            await connection.InvokeAsync("SendMessage""jack""hello,world");

            Console.ReadLine();
        }
    }

接下来就可以调试一下,分别启动 server 和 client 端,如下图所示:

server

client

译文链接:https://www.infoworld.com/article/3267165/how-to-use-signalr-in-aspnet-core.html


本文分享自微信公众号 - 一线码农聊技术(dotnetfly)。
如有侵权,请联系 [email protected] 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章