hslcommunication心跳处理

利用hslcommunication库定时发送心跳信号,判断网络状态是否良好。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Threading;
using System.Threading.Tasks;
using HslCommunication;
using HslCommunication.Core.Net;

public class HeartBeatClient
{
private readonly EasyTcpClient _client;
private readonly CancellationTokenSource _cancellationTokenSource;

public HeartBeatClient()
{
_cancellationTokenSource = new CancellationTokenSource();
_client = new EasyTcpClient();

_clientHeartbeatInterval = 5000;

_client.ConnectTimeOut = 5000;
_client.HeartBeatTimeOut = 10000;

_client.ReceiveTimeout = 5000;
_client.SendTimeout = 5000;

_client.OnNetworkError += OnNetworkError;
}

public async Task ConnectAsync(string ipAddress, int port)
{
await _client.ConnectAsync(ipAddress, port, _cancellationTokenSource.Token);
StartHeartbeatThread();
}

private readonly int _clientHeartbeatInterval;
private void StartHeartbeatThread()
{
Task.Factory.StartNew(async () =>
{
while (!_cancellationTokenSource.IsCancellationRequested)
{
try
{
// 发送心跳
_client.Send(new byte[] { 0x0 });

await Task.Delay(_clientHeartbeatInterval, _cancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
OnNetworkError(_client, ex);
}
}
}, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}

public bool IsConnected
{
get => _client.IsConnected;
}

public void Disconnect()
{
_cancellationTokenSource.Cancel();
_client.Disconnect();
}

private void OnNetworkError(object sender, Exception e)
{
// TODO: 处理网络错误
}
}
// 可以根据自己的需求调整心跳时间和超时时间,另外,对于网络错误也需要在 OnNetworkError 函数中做相应的处理。