WinForms 应用程序中使用 SignalR 连接到服务器

安装

bash 复制代码
dotnet Install Microsoft.AspNetCore.SignalR.Client

WinForms 应用程序中使用 SignalR 连接到服务器时

  • 安装 SignalR 客户端库:使用 NuGet 包管理器安装 SignalR 客户端库。
  • 创建 SignalR 连接:在代码中创建 SignalR 连接,并指定服务器端点。
  • 定义 SignalR Hub 方法:定义客户端将调用的方法。
  • 处理连接和消息:处理连接的生命周期事件以及从服务器接收的消息。

以下是一个简单的示例,演示如何在 WinForms 中连接到 SignalR 服务器:

csharp 复制代码
using System;
using Microsoft.AspNetCore.SignalR.Client;
using System.Windows.Forms;

namespace SignalRWinFormsExample
{
    public partial class MainForm : Form
    {
        private HubConnection _connection;

        public MainForm()
        {
            InitializeComponent();
        }

        private async void MainForm_Load(object sender, EventArgs e)
        {
            // 1. 创建 SignalR 连接
            _connection = new HubConnectionBuilder()
                .WithUrl("http://your-server-url/signalrHub") // 替换为您的服务器端点
                .Build();

            // 2. 定义客户端方法
            _connection.On<string>("ReceiveMessage", message =>
            {
                // 收到消息后的处理
                Invoke(new Action(() =>
                {
                    listBoxMessages.Items.Add(message);
                }));
            });

            // 3. 连接到服务器
            try
            {
                await _connection.StartAsync();
                MessageBox.Show("Connected to server");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error connecting to server: {ex.Message}");
            }
        }

        private async void buttonSend_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBoxMessage.Text))
            {
                try
                {
                    // 4. 发送消息到服务器
                    await _connection.InvokeAsync("SendMessage", textBoxMessage.Text);
                    textBoxMessage.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Error sending message: {ex.Message}");
                }
            }
            else
            {
                MessageBox.Show("Please enter a message to send.");
            }
        }

        private async void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 5. 断开连接
            if (_connection != null)
            {
                await _connection.DisposeAsync();
            }
        }
    }
}

假设您已经在服务器端实现了名为 SignalRHub 的 SignalR Hub,并且该 Hub 包含了一个名为 SendMessage 的方法,用于接收来自客户端的消息,并将其广播给所有连接的客户端。客户端在收到消息时调用名为 ReceiveMessage 的方法来处理。

相关推荐
北漂Zachary4 分钟前
四大编程语言终极对决:汇编/C#/Go/Java谁更强
汇编·golang·c#
nnsix3 小时前
C# ProcessStartInfo对象笔记
开发语言·笔记·c#
格林威4 小时前
工业相机“心跳”监测脚本(C# 版) 支持海康 / Basler / 堡盟工业相机
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测
刚子编程6 小时前
C#事务处理最佳实践:别再让“主表存了、明细丢了”的破事发生
开发语言·c#·事务处理·trycatch
斯卡文计算机术士6 小时前
C#测试(二)
c#
manyikaimen6 小时前
博派智能-运动控制技术-C#环境的搭建
c#·环境搭建·运动控制器·运动控制卡·动态库调用
xiaoshuaishuai817 小时前
C# GPU算力与管理
开发语言·windows·c#
hez201019 小时前
C# 15 类型系统改进:Union Types
c#·.net·.net core
FL162386312919 小时前
基于C#winform部署软前景分割DAViD算法的onnx模型实现前景分割
开发语言·算法·c#
C#程序员一枚20 小时前
高可用(High Availability, HA)
数据库·c#