在使用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();