ASP.Net Core 中使用 SignalR

枫殇NET开发
2021-04-06 / 0 评论 / 230 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年06月02日,已超过1021天没有更新,若内容或图片失效,请留言反馈。

SignalR

什么是SignalR

SignalR for ASP.Net Core是微软开发的一套实时通讯解决方案,其兼容实现了websocketServer-Sent 事件长轮询等机制,并且会自动选择服务器和客户端功能内的最佳传输方法。另外,ASP.Net Core版本的SignalR相比.Net FrameWork平台下的SignalR并不完全一致,有较大的的改动且移除了原.Net FrameWork下的诸多功能,如:自动重连机制消息处理机制单连接多hub等。并对客户端采用的是TypeScript进行了重写。总的来说,新版本已不兼容老版本。

安装 SignalR 服务端

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

Install-Package Microsoft.AspNetCore.SignalR

配置 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 broadcast

创建一个自定义的 MessageHub 类并继承类库中的 Hub 基类,在 MessageHub 中定义一个 SendMessage 方法,该方法用于向所有已连接的客户端发送消息,如下代码所示:

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

创建 SignalR client

SignalR 的 client 是跨平台的,在.Net平台中使用需要引用 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<string, string>("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

server

client

client

0

评论 (0)

取消