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

相关推荐
番茄小能手42 分钟前
【全网唯一】C# 纯本地离线文字识别Windows版dll插件
开发语言·c#
葬歌倾城1 小时前
waferMap图像渲染
c#·wpf
甄天2 小时前
WPF路由事件:冒泡、隧道与直接全解析
c#·wpf·visual studio
专注VB编程开发20年3 小时前
C#,VB.NET从JSON数据里提取数组中的对象节点值
c#·json·.net
Accpdaiyekun5 小时前
C# 操作mongodb 多次查询快还是使用管道查询速度快
mongodb·c#·lua
界面开发小八哥5 小时前
界面组件DevExpress WPF中文教程:Grid - 如何获取节点?
.net·wpf·界面控件·devexpress·ui开发
Dm_dotnet5 小时前
C#:wpf ui 4.0 是如何实现页面导航的?
c#
今晚打老虎z6 小时前
dotnet-env: .NET 开发者的环境变量加载工具
前端·chrome·.net
圆滚滚肉肉7 小时前
后端MVC(控制器与动作方法的关系)
后端·c#·asp.net·mvc
ajassi20007 小时前
开源 C# .net mvc 开发(六)发送邮件、定时以及CMD编程
linux·开源·c#·mvc