C# Socket 心跳重连

发布时间 2023-10-17 10:31:30作者: 子凡。翅膀

//需要引用  SuperSocket.ClientEngine

 

  1 using SuperSocket.ClientEngine;
  2 using System;
  3 using System.Collections.Generic;
  4 using System.Linq;
  5 using System.Text;
  6 using System.Net;
  7 using System.Threading.Tasks;
  8 
  9 namespace aaa.aaa.Core
 10 {
 11 public class MonitorClientCommCore
 12 {
 13 string _Ip = null;
 14 int _Port = 0;
 15 string _SendContent = null;
 16 static AsyncTcpSession client;
 17 static System.Timers.Timer timer = null;
 18 int _HeartbeatTime = 0;
 19 public MonitorClientCommCore(string Ip, int Port, string SendContent, int HeartbeatTime = 1)
 20 {
 21 this._Ip = Ip;
 22 this._Port = Port;
 23 this._SendContent = SendContent;
 24 this._HeartbeatTime = HeartbeatTime;
 25 }
 26 public void Start()
 27 {
 28 try
 29 {
 30 Link(_HeartbeatTime);
 31 while (true)
 32 {
 33 if (client != null && client.IsConnected)
 34 {
 35 Thread.Sleep(5000);
 36 var msg = System.Text.Encoding.UTF8.GetBytes("echo hello " + _SendContent + "\r\n");
 37 client.Send(msg, 0, msg.Length);
 38 }
 39 }
 40 }
 41 catch (Exception ex)
 42 {
 43 Link(_HeartbeatTime);
 44 Log.Error("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "--错误:" + ex.Message);
 45 }
 46 }
 47 
 48 /// <summary>
 49 /// 心跳重连时间
 50 /// </summary>
 51 /// <param name="HeartbeatTime"></param>
 52 public void Link(int HeartbeatTime)
 53 {
 54 HeartbeatTime = HeartbeatTime * 1000;
 55 client = new AsyncTcpSession();
 56 client.Connected += OnClientConnected;
 57 client.Error += OnClientError;
 58 client.Closed += OnClientClosed;
 59 // 收到服务器数据事件
 60 client.DataReceived += client_DataReceived;
 61 
 62 //每10s发送一次心跳或尝试一次重连
 63 timer = new System.Timers.Timer(HeartbeatTime);
 64 timer.Elapsed += new System.Timers.ElapsedEventHandler((s, x) =>
 65 {
 66 //心跳包
 67 if (client.IsConnected)
 68 {
 69 var heartMsg = System.Text.Encoding.Default.GetBytes("echo heart \r\n");
 70 client.Send(heartMsg, 0, heartMsg.Length);
 71 }
 72 //断线重连
 73 else if (!client.IsConnected)
 74 {
 75 client.Connect(new IPEndPoint(IPAddress.Parse(_Ip), _Port));
 76 }
 77 });
 78 timer.Enabled = true;
 79 timer.Start();
 80 
 81 }
 82 void OnClientConnected(object sender, EventArgs e)
 83 {
 84 Log.Info("已连接" + _Ip + _Port.ToString() + '\n');
 85 }
 86 void OnClientClosed(object sender, EventArgs e)
 87 {
 88 Log.Info("已断开" + _Ip + _Port.ToString() + '\n');
 89 }
 90 void OnClientError(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
 91 {
 92 Log.Error($"错误:{e.Exception.Message}" + '\n');
 93 }
 94 void client_DataReceived(object sender, DataEventArgs e)
 95 {
 96 string msg = Encoding.UTF8.GetString(e.Data);
 97 Log.Info(msg.Trim('\0'));
 98 }
 99 }
100 }

 

 

//调用

Task.Run(() =>
{
MonitorClientCommCore mcc = new MonitorClientCommCore(Ip, port, "发送 我爱黎明!", 10);//ip,端口
mcc.Start();
});