signalr连接服务器成功后自动断开

本文介绍了如何在SignalR开发中通过设置定时发送心跳消息来防止客户端和服务端的定期断开连接,包括C#代码示例和连接中断处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用signalr开发的时候,发现客户端连接服务端成功之后,间隔一段较为规律的时间,服务端会和客户端断开连接。然后找了很久,找到使用一个心跳机制可解决这个问题

以下是一个简单的 SignalR 客户端实现心跳机制的示例(使用 C#):

var connection = new HubConnectionBuilder()
            .WithUrl("http://localhost:5000/chatHub")
            .Build();

        // 心跳时间间隔(单位:毫秒)
        int heartbeatInterval = 5000;

        // 启动连接
        await connection.StartAsync();

        // 定时发送心跳消息
        var heartbeatTimer = new System.Timers.Timer(heartbeatInterval);
        heartbeatTimer.Elapsed += async (sender, e) =>
        {
            try
            {
                // 发送心跳消息
                await connection.SendAsync("Heartbeat");
            }
            catch (Exception ex)
            {
                // 发送心跳消息失败,处理异常
                Console.WriteLine($"Error sending heartbeat: {ex.Message}");
            }
        };
        heartbeatTimer.Start();

        // 处理连接中断
        connection.Closed += async (error) =>
        {
            Console.WriteLine($"Connection closed: {error?.Message}");
            // 重新连接
            await Task.Delay(5000); // 5 秒后重试
            await connection.StartAsync();
        };

        // 接收服务器端心跳响应(可选)
        connection.On("HeartbeatResponse", () =>
        {
            Console.WriteLine("Received heartbeat response from server.");
        });

        // 阻止主线程退出
        Console.ReadLine();

        // 停止心跳定时器
        heartbeatTimer.Stop();

        // 关闭连接
        await connection.StopAsync();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值