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

相关推荐
绿荫阿广3 小时前
互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(五):使用.NET为树莓派开发Wifi配网功能
c#·.net
唐青枫6 小时前
.NET AOT 详解
.net
ou.cs6 小时前
c# :this() 和 :base()区别
开发语言·c#
汪小白JIY9 小时前
【C#】异步和多线程
c#·thread·async·task·threapool
AI.NET 极客圈10 小时前
.NET 原生驾驭 AI 新基建实战系列(六):Pinecone ── 托管向量数据库的向量数据库的云原生先锋
数据库·人工智能·.net
宝桥南山10 小时前
DeepSeek - 尝试一下GitHub Models中的DeepSeek
microsoft·ai·微软·c#·github·.net
追逐时光者10 小时前
C#/.NET/.NET Core优秀项目和框架2025年5月简报
后端·.net
lljss202017 小时前
C# 一个解决方案放一个dll项目,一个dll测试项目 ,调试dll项目的源码
c#
ghost1431 天前
C#学习第27天:时间和日期的处理
开发语言·学习·c#
jason成都1 天前
c#压缩与解压缩-SharpCompress
开发语言·c#