代码改变世界

Socket 心跳 第二篇

2023-10-20 10:36  子凡。翅膀  阅读(24)  评论(1编辑  收藏  举报
 

首先需要引用 

using SuperSocket.ProtoBase;
using SuperSocket.ClientEngine;

 

 

 

  1 public class bb
  2     {
  3         static EasyClient<MyPackageInfo> client = null;
  4         static System.Timers.Timer timer = null;
  5         string _Ip = null;
  6         int _Port = 0;
  7         string _SendContent = null;
  8         int _HeartbeatTime = 0;
  9         public MonitorClientCommCoreTwo(string Ip, int Port, string SendContent, int HeartbeatTime = 1)
 10         {
 11             this._Ip = Ip;
 12             this._Port = Port;
 13             this._SendContent = SendContent;
 14             this._HeartbeatTime = HeartbeatTime;
 15         }
 16         public async void connectServer()
 17         {
 18             client = new EasyClient<MyPackageInfo>();
 19             client.Initialize(new MyReceiveFilter());
 20             client.Connected += OnClientConnected;
 21             client.NewPackageReceived += OnPackageReceived;
 22             client.Error += OnClientError;
 23             client.Closed += OnClientClosed;
 24             var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse(_Ip), _Port));
 25             if (connected)
 26             {
 27                 //name 2 length 2 body 6 bit 心跳包
 28                 var rs = new List<byte> { 0, 1, 0, 6 };
 29                 rs.AddRange(System.Text.Encoding.UTF8.GetBytes("--发送数据:"+_SendContent +"   Time:"+ DateTime.Now.ToString("1ssfff")));
 30 
 31                 LogUtils.Info("发送数据:" + DataHelper.ByteToHex(rs.ToArray(), rs.Count));
 32                 client.Send(rs.ToArray());
 33 
 34 
 35                 //每5秒发一次心跳
 36                 timer = new System.Timers.Timer(_HeartbeatTime * 1000);
 37                 timer.Elapsed += new System.Timers.ElapsedEventHandler((s, x) =>
 38                 {
 39                     if (client.IsConnected)
 40                     {
 41                         rs = new List<byte> { 0, 2, 0, 6 };
 42                         rs.AddRange(DateTime.Now.ToString("yy MM dd HH mm ss").Split(' ').Select(m => byte.Parse(m)).ToArray());
 43 
 44                         LogUtils.Info("发送数据:" + DataHelper.ByteToHex(rs.ToArray(), rs.Count));
 45                         client.Send(rs.ToArray());
 46                     }
 47                 });
 48                 timer.Enabled = true;
 49                 timer.Start();
 50             }
 51             else
 52             {
 53                 LogUtils.Info("连接服务器失败");
 54             }
 55         }
 56 
 57         private void OnPackageReceived(object sender, PackageEventArgs<MyPackageInfo> e)
 58         {
 59             LogUtils.Info("收到文本下行:" + e.Package.Body);
 60             //16进制
 61             //LogHelper.WriteLog("下行:" + DataHelper.ByteToHex(e.Package.Header, e.Package.Header.Length) + DataHelper.ByteToHex(e.Package.Data, e.Package.Data.Length));
 62 
 63             //回复服务端确认
 64             if ((e.Package.Header[0] * 256 + e.Package.Header[1]) == 4)
 65             {
 66                 var arr = new List<byte> { 0, 4, 0, 1, 1 };
 67                 client.Send(arr.ToArray());
 68             }
 69         }
 70 
 71         private void OnClientConnected(object sender, EventArgs e)
 72         {
 73             LogUtils.Info("已连接到服务器...");
 74         }
 75 
 76         private void OnClientClosed(object sender, EventArgs e)
 77         {
 78             if (timer != null)
 79             {
 80                 timer.Dispose();
 81             }
 82             LogUtils.Info("连接已断开...");
 83         }
 84 
 85         private void OnClientError(object sender, object e)
 86         {
 87             LogUtils.Info("客户端错误:");
 88         }
 89 
 90         private void btnConn_Click(object sender, EventArgs e)
 91         {
 92             if (client == null || !client.IsConnected)
 93                 connectServer();
 94         }
 95     }
 96     public class DataHelper
 97     {
 98         public static string ByteToHex(byte comByte)
 99         {
100             return comByte.ToString("X2") + " ";
101         }
102         public static string ByteToHex(byte[] comByte, int len)
103         {
104             string returnStr = "";
105             if (comByte != null)
106             {
107                 for (int i = 0; i < len; i++)
108                 {
109                     returnStr += comByte[i].ToString("X2") + " ";
110                 }
111             }
112             return returnStr;
113         }
114         public static byte[] HexToByte(string msg)
115         {
116             msg = msg.Replace(" ", "");
117 
118             byte[] comBuffer = new byte[msg.Length / 2];
119             for (int i = 0; i < msg.Length; i += 2)
120             {
121                 comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
122             }
123 
124             return comBuffer;
125         }
126         public static string HEXToASCII(string data)
127         {
128             data = data.Replace(" ", "");
129             byte[] comBuffer = new byte[data.Length / 2];
130             for (int i = 0; i < data.Length; i += 2)
131             {
132                 comBuffer[i / 2] = (byte)Convert.ToByte(data.Substring(i, 2), 16);
133             }
134             string result = Encoding.Default.GetString(comBuffer);
135             return result;
136         }
137         public static string ASCIIToHEX(string data)
138         {
139             StringBuilder result = new StringBuilder(data.Length * 2);
140             for (int i = 0; i < data.Length; i++)
141             {
142                 result.Append(((int)data[i]).ToString("X2") + " ");
143             }
144             return Convert.ToString(result);
145         }
146     }
147     public class MyReceiveFilter : FixedHeaderReceiveFilter<MyPackageInfo>
148     {
149         /// +-------+---+-------------------------------+
150         /// |request| l |                               |
151         /// | name  | e |    request body               |
152         /// |  (2)  | n |                               |
153         /// |       |(2)|                               |
154         /// +-------+---+-------------------------------+
155         public MyReceiveFilter()
156         : base(4)
157         {
158 
159         }
160         protected override int GetBodyLengthFromHeader(IBufferStream bufferStream, int length)
161         {
162             ArraySegment<byte> buffers = bufferStream.Buffers[0];
163             byte[] array = buffers.ToArray();
164             int len = array[length - 2] * 256 + array[length - 1];
165             //int len = (int)array[buffers.Offset + 2] * 256 + (int)array[buffers.Offset + 3];
166             return len;
167         }
168         public override MyPackageInfo ResolvePackage(IBufferStream bufferStream)
169         {
170             //第三个参数用0,1都可以
171             byte[] header = bufferStream.Buffers[0].ToArray();
172             byte[] bodyBuffer = bufferStream.Buffers[1].ToArray();
173             byte[] allBuffer = bufferStream.Buffers[0].Array.CloneRange(0, (int)bufferStream.Length);
174             return new MyPackageInfo(header, bodyBuffer);
175         }
176     }
177 
178 
179     public class MyPackageInfo : IPackageInfo
180     {
181         public MyPackageInfo(byte[] header, byte[] bodyBuffer)
182         {
183             Header = header;
184             Data = bodyBuffer;
185         }
186         /// <summary>
187         /// 服务器返回的字节数据头部
188         /// </summary>
189         public byte[] Header { get; set; }
190         /// <summary>
191         /// 服务器返回的字节数据
192         /// </summary>
193         public byte[] Data { get; set; }
194         /// <summary>
195         /// 服务器返回的字符串数据
196         /// </summary>
197         public string Body
198         {
199             get
200             {
201                 return Encoding.UTF8.GetString(Data);
202             }
203         }

 

//调用时

Task.Run(() =>
{
bb mcc = new bb(Ip, port, "发送 我爱黎明!", 5);
mcc.connectServer();
});