天天看點

.Net Core平台下實作SignalR用戶端和服務端

一、SignalR服務端

1、建立Asp.Net Core 空模闆

.Net Core平台下實作SignalR用戶端和服務端

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.cs 類

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平台下的控制台應用程式

.Net Core平台下實作SignalR用戶端和服務端

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}");
        }
    }
           

繼續閱讀