using AKSWebBrowser.Commen; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Net; using System.Net.Http; using System.IO.Ports; using System.Timers; using AksWebBrowser; namespace AksWebBrowser.Common { public class TcpClients { public string jsonstr = string.Empty; /// /// 打开连接 /// public TcpClients() { try { //初始化连接 192.168.1.166 Parame.tcpClient = new TcpClient(Parame.Ip, 1234); NetworkStream stream = Parame.tcpClient.GetStream(); Task.Factory.StartNew(() => { Write(stream); }); ThreadPool.QueueUserWorkItem(SendInstruction, Parame.tcpClient); } catch { Parame.tcpClient = null; } finally { //开启定时 System.Timers.Timer timer = new System.Timers.Timer(1000);//3秒钟的时间间隔 timer.Elapsed += OnTimedEvent; timer.AutoReset = true;//重复执行 timer.Enabled = true;//启动定时器 } } //打开串口 private void OnTimedEvent(Object source, ElapsedEventArgs e) { try { if (Parame.tcpClient == null) { Parame.tcpClient = new TcpClient(Parame.Ip, 1234); NetworkStream stream = Parame.tcpClient.GetStream(); Task.Factory.StartNew(() => { Write(stream); }); ThreadPool.QueueUserWorkItem(SendInstruction, Parame.tcpClient); } } catch { Parame.tcpClient = null; } finally { } } /// /// 读取服务端信息 /// /// public void Write(NetworkStream stream) { while (true) { try { // 读取包头,获取消息的大小 int messageSize = ReadHeader(stream); if (messageSize == -1) { Parame.tcpClient = null; //Console.WriteLine("与服务端连接断开"); break; } // 读取消息内容 byte[] buffer = new byte[messageSize]; int bytesRead = ReadExactly(stream, buffer, 0, messageSize); if (bytesRead < messageSize) { Parame.tcpClient = null; //Console.WriteLine("无法读取消息,可能是连接断开"); break; } string message = Encoding.UTF8.GetString(buffer, 0, bytesRead); if (!message.Contains("heartbeatService")) { //接收到服务端口返回数据 //Console.WriteLine("接收到服务端口返回数据:{0}", message); jsonstr = message; } else { //收到服务器心跳反馈 //Console.WriteLine("收到服务器心跳反馈:{0}", message); SendDataWithHeader(stream, "heartbeatClient"); } } catch { jsonstr = string.Empty; Parame.tcpClient = null; } finally { } } } /// /// 发送信息给服务端 /// /// /// public string SendDataWithHeader(NetworkStream stream, string message) { try { int timeout = 0; byte[] messageBytes = Encoding.UTF8.GetBytes(message); byte[] header = BitConverter.GetBytes(messageBytes.Length); byte[] data = new byte[header.Length + messageBytes.Length]; Array.Copy(header, 0, data, 0, header.Length); Array.Copy(messageBytes, 0, data, header.Length, messageBytes.Length); stream.Write(data, 0, data.Length); jsonstr = string.Empty; while (string.IsNullOrEmpty(jsonstr) && Parame.tcpClient != null) { Task.Delay(10).Wait(); timeout = timeout + 10; if (timeout > 9000) { jsonstr = MainModel.str2Base64("{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "获取数据超时!" + "\"}"); } } if (string.IsNullOrEmpty(jsonstr)) { jsonstr = MainModel.str2Base64("{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "硬件服务器未启动" + "\"}"); } } catch { Parame.tcpClient = null; } finally { } return jsonstr; } /// /// 发送心跳 /// /// public void SendInstruction(object state) { try { TcpClient client = (TcpClient)state; NetworkStream stream = client.GetStream(); while (true) { // 每隔2分钟向服务端发送一条指令 Thread.Sleep(122000); SendDataWithHeader(stream, "keepAlive"); //Console.WriteLine("发送心跳指令关闭连接"); } } catch { Parame.tcpClient = null; } finally { } } /// /// 解析包头中有多少字节 /// /// /// public int ReadHeader(NetworkStream stream) { try { byte[] header = new byte[4]; int headerBytesRead = stream.Read(header, 0, 4); if (headerBytesRead < 4) { Parame.tcpClient = null; //Console.WriteLine("无法读取包头,可能是连接断开"); return -1; } return BitConverter.ToInt32(header, 0); } catch { Parame.tcpClient = null; return -1; } } /// /// 等待流全部获取到,然后丢出去 /// /// /// /// /// /// public int ReadExactly(NetworkStream stream, byte[] buffer, int offset, int count) { try { int bytesRead = 0; while (bytesRead < count) { int result = stream.Read(buffer, offset + bytesRead, count - bytesRead); if (result == 0) { // 连接断开或遇到流的末尾 return bytesRead; } bytesRead += result; } return bytesRead; } catch { Parame.tcpClient = null; return -1; } } } }