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

相关推荐
正运动技术7 小时前
PC强实时运动控制(一):C#的EtherCAT总线初始化(上)
c#·运动控制·正运动技术·运动控制器·ethercat·正运动·运动控制内核
d111111111d7 小时前
在STM32中,中断服务函数的命名有什么要求?
笔记·stm32·单片机·嵌入式硬件·学习·c#
极客智造8 小时前
深入解析 C# Type 类:解锁反射与动态编程的核心
c#·反射
SmoothSailingT9 小时前
C#——textBox控件(1)
开发语言·c#
superman超哥9 小时前
仓颉语言中并发集合的实现深度剖析与高性能实践
开发语言·后端·python·c#·仓颉
工程师0079 小时前
C#中的服务注册剖析
c#·服务注册
张人玉10 小时前
c#DataTable类
数据库·c#
缺点内向10 小时前
如何在 C# .NET 中将 Markdown 转换为 PDF 和 Excel:完整指南
pdf·c#·.net·excel
CodeCraft Studio10 小时前
Excel处理控件Aspose.Cells教程:使用C#在Excel中创建旭日图
c#·excel·aspose·excel旭日图·excel库·excel开发控件·excel api库