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 的方法来处理。

相关推荐
Eiceblue42 分钟前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html
IUGEI1 小时前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#
棉晗榜3 小时前
无法解析位于...\global.json 的 global.json 中指定的 .NET SDK 版本
.net
czhc11400756633 小时前
C# 1124 接收
开发语言·c#
时光追逐者5 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 62 期(2025年11.17-11.23)
c#·.net·.netcore
司铭鸿5 小时前
祖先关系的数学重构:从家谱到算法的思维跃迁
开发语言·数据结构·人工智能·算法·重构·c#·哈希算法
宝桥南山8 小时前
.NET 10 - Blazor web assembly应用的一些诊断方式
microsoft·微软·c#·asp.net·.net·.netcore
sz老兄闯8 小时前
对 .NET FileSystemWatcher引发内存碎片化的 反思
.net
m0_6265352010 小时前
代码分析
开发语言·c#