.Net Core平台下实现SignalR客户端和服务端

时间:2024-03-13 20:34:23

一、SignalR服务端

1、新建Asp.Net Core 空模板

 

 

2、 修改launchsettings.json文件

{
 
  "profiles": {
    
    "SignalRSeverCore": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": false,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

3、添加TestHub.cs 类

public class TestHub : Hub
    {

        public async Task Send(string name, string message)
        {
            Console.WriteLine($"用户名称{name},收到消息{message}");
            await Clients.All.SendAsync("myMessage", name, message);
        }


        public override async Task OnConnectedAsync()
        {
            Console.WriteLine($"建立连接{Context.ConnectionId}");
            await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
            await base.OnConnectedAsync();
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            Console.WriteLine($"断开连接{Context.ConnectionId}");
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users");
            await base.OnDisconnectedAsync(exception);
        }
    }

4、修改 Startup 类

  public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<TestHub>("/myTestHub");
            });
        }
    }

 

二、SignalR 客户端

1、新建 .Net Core平台下的控制台应用程序

 

 

2、Nuget包下载安装

Microsoft.AspNetCore.SignalR.Client 

3、修改Program.cs 文件

 class Program
    {
        const string url = @"http://127.0.0.1:5000/myTestHub";
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            HubConnection hubConnection = new HubConnectionBuilder()
                .WithUrl(url)
                .Build();
            hubConnection.On<string, string>("myMessage", (s1, s2) =>
              OnSend(s1, s2)
            );
            hubConnection.Closed += HubConnection_Closed;
            await hubConnection.StartAsync();
            Console.WriteLine($"连接状态:{hubConnection.State}");

            await hubConnection.InvokeAsync("Send", "Test1", "Hello World");


            var command = Console.ReadLine();
            if (command == "exit")
            {
               await hubConnection.StopAsync();
            }
            Console.ReadKey();
        }

        private static System.Threading.Tasks.Task HubConnection_Closed(Exception arg)
        {
            return Task.Run(() =>
            {
                Console.WriteLine($"连接断开");
                Console.WriteLine(arg.Message);
            });
        }

        private static void OnSend(string s1, string s2)
        {
            Console.WriteLine($"用户名称{s1},消息内容{s2}");
        }
    }