zoukankan      html  css  js  c++  java
  • .Net Core平台下实现SignalR客户端和服务端

    一、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}");
            }
        }
  • 相关阅读:
    20175215 2018-2019-2 第十周java课程学习总结
    2018-2019-2 20175215 实验三《敏捷开发与XP实践》实验报告
    MyCP(课下作业,必做)
    2018-2019-1 20175234 《信息安全系统设计基础》有关系统调用的部分学习
    2018-2019-1 20175234 《信息安全系统设计基础》第2周学习总结
    一个想要拥有正常的F1~F12的联想小新潮
    2018-2019-1 20175234 《信息安全系统设计基础》第1周学习总结
    Visual C++ 6.0精简绿色版下载及简单使用教程
    20175234 2018-2019-2 实验五 网络编程与安全
    20175234 2018-2019-2 实验四 Android程序设计
  • 原文地址:https://www.cnblogs.com/lhwpc/p/15149679.html
Copyright © 2011-2022 走看看