.net 8.0 下 Blazor 通过 SignalR 与 Winform 交互

打印 上一主题 下一主题

主题 546|帖子 546|积分 1638

界说一个Hub
  1. using Microsoft.AspNetCore.SignalR;
  2. namespace Beatrane.Connect.Blazor
  3. {
  4.     public class DeviceHub : Hub
  5.     {
  6.         public async Task SendMessage(string user, string message)
  7.         {
  8.             await Clients.All.SendAsync("ReceiveMessage", user, message);
  9.         }
  10.         public async Task UpdateOnlineStatus(string deviceId, string status)
  11.         {
  12.             await Clients.All.SendAsync("OnlineStatusUpdated", deviceId, status);
  13.         }
  14.     }
  15. }
复制代码
程序初始化的时候要注册这个Hub
  1.             const string hubsPrefix = "/hubs";
  2.             app.MapGroup(hubsPrefix).MapHub<DeviceHub>("/devicehub");
复制代码
在 Blazor 的一个页面吸收来自客户端 Winform 的消息
  1.     private HubConnection? _hubConnection;
  2.     private string? _deviceId;
  3.     private string? _status;
  4.     protected override async Task OnInitializedAsync()
  5.     {
  6.         try
  7.         {
  8.             var url = NavigationManager.ToAbsoluteUri("/hubs/devicehub");
  9.             _hubConnection = new HubConnectionBuilder()
  10.                 .WithUrl(url)
  11.                 .Build();
  12.             _hubConnection.On<string, string>("OnlineStatusUpdated", async (deviceId, status) =>
  13.             {
  14.                 _deviceId = deviceId;
  15.                 _status = status;
  16.                 await InvokeAsync(StateHasChanged);
  17.             });
  18.             _hubConnection.Closed += async (error) =>
  19.             {
  20.                 Console.WriteLine("Connection closed: " + error);
  21.                 await Task.Delay(new Random().Next(0, 5) * 1000);
  22.                 await _hubConnection.StartAsync();
  23.             };
  24.             await _hubConnection.StartAsync();
  25.         }
  26.         catch (Exception e)
  27.         {
  28.             Console.WriteLine(e);
  29.             throw;
  30.         }
  31.     }
复制代码
留意以下,下面说的是一个坑点,SignalR 的包,  VS 默认会建议你安装
  1. Microsoft.AspNetCore.SignalR.Client.Core
复制代码
但实际你要安装的是
  1. Microsoft.AspNetCore.SignalR.Client
复制代码
不然会少一个扩展类,没有 WithUrl 方法可以用了
那么上面Blazor服务端的事就做完了,非常简朴。下面是Winform 客户端。因为咱利用的是 https,所以还有个连接时证书验证的题目。这里利用 clientHandler.ServerCertificateCustomValidationCallback = ValidateServerCertificate 直接返回 True 。等真的须要验证了再改写 ValidateServerCertificate 方法的逻辑
  1. using Microsoft.AspNetCore.SignalR.Client;
  2. using System.Net.Security;
  3. using System.Security.Cryptography.X509Certificates;
  4. namespace WinFormsApp1
  5. {
  6.     public partial class Form1 : Form
  7.     {
  8.         private HubConnection _hubConnection;
  9.         public Form1()
  10.         {
  11.             InitializeComponent();
  12.         }
  13.         private bool ValidateServerCertificate(HttpRequestMessage message, X509Certificate2? certificate, X509Chain? chain, SslPolicyErrors errors)
  14.         {
  15.             return true;
  16.         }
  17.         private async void button1_Click(object sender, EventArgs e)
  18.         {
  19.             try
  20.             {
  21.                 if (_hubConnection is { State: HubConnectionState.Connected })
  22.                 {
  23.                     await _hubConnection.InvokeAsync(@"UpdateOnlineStatus", Guid.NewGuid().ToString(), "Online");
  24.                 }
  25.                 else
  26.                 {
  27.                     var url = @"https://localhost:5001/hubs/devicehub";
  28.                     _hubConnection = new HubConnectionBuilder()
  29.                         .WithUrl(url, options =>
  30.                         {
  31.                             options.HttpMessageHandlerFactory = handler =>
  32.                             {
  33.                                 if (handler is HttpClientHandler clientHandler)
  34.                                 {
  35.                                     clientHandler.ServerCertificateCustomValidationCallback = ValidateServerCertificate;
  36.                                 }
  37.                                 return handler;
  38.                             };
  39.                         })
  40.                         .WithAutomaticReconnect()
  41.                         .Build();
  42.                     _hubConnection.ServerTimeout = TimeSpan.FromSeconds(5);
  43.                     await _hubConnection.StartAsync();
  44.                     await _hubConnection.InvokeAsync(@"UpdateOnlineStatus", Guid.NewGuid().ToString(), "Online");
  45.                 }
  46.             }
  47.             catch (Exception ex)
  48.             {
  49.                 Console.WriteLine(ex);
  50.             }
  51.         }
  52.     }
  53. }
复制代码
这个时候就可以把两端的程序跑来做验证了

每点击一次 Button1 ,Blazor 的网页端就会收到新的 guid。如此,通信便完成了 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

欢乐狗

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表