hslcommunication心跳处理 发表于 2023-06-01 | 分类于 hsl | 字数统计: 231 | 阅读时长 ≈ 1利用hslcommunication库定时发送心跳信号,判断网络状态是否良好。12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576using 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 函数中做相应的处理。