From ea0b1e8e5f43c5fd0a7d479e25ede3b8cbea464a Mon Sep 17 00:00:00 2001 From: wxr <wxr@hdlchina.com.cn> Date: 星期一, 02 十二月 2024 17:17:19 +0800 Subject: [PATCH] tcp;可视对讲; --- HDL_ON/DAL/DriverLayer/Control_TcpClient.cs | 507 ++++++++++++++++++------------------------------------- 1 files changed, 169 insertions(+), 338 deletions(-) diff --git a/HDL_ON/DAL/DriverLayer/Control_TcpClient.cs b/HDL_ON/DAL/DriverLayer/Control_TcpClient.cs index 84e305b..28edb3c 100644 --- a/HDL_ON/DAL/DriverLayer/Control_TcpClient.cs +++ b/HDL_ON/DAL/DriverLayer/Control_TcpClient.cs @@ -1,10 +1,7 @@ 锘縰sing System; using System.Collections.Generic; -using System.Net; using System.Net.Sockets; using System.Threading; -using System.Threading.Tasks; -using HDL_ON.Entity; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -12,70 +9,13 @@ { public class Control_TcpClient { - //澹版槑IP锛岀鍙o紝鍜屼竴涓敤鏉ヨ繛鎺ョ殑Socket - public string _ip; + private string _ip; - private TcpClient _clinet; - - private TcpClient _tcpClient { - get - { - return _clinet; - } - set - { - _clinet = value; - if (_clinet == null) { - if(connectThread!= null) - { - connectThread.Abort(); - connectThread = null; - } - } - } - } - + private bool run = true; + private bool reconnect; //鍒涘缓涓�涓鎵橈紝鐢ㄦ潵婊¤冻鍏朵粬绫昏皟鐢� - //public delegate void DelegateMessage(string str); public Action<string> ReceiveEvent; - - /// <summary> - /// 杩炴帴娆℃暟 - /// </summary> - private int reconnectIndex = 0; - - private bool _isConnected = false; - /// <summary> - /// 鏄惁杩炴帴鎴愬姛 - /// </summary> - public bool isConnected { - get - { - return _isConnected; - } - set - { - _isConnected = value; - if (value) - { - Control.Ins.LoginGateway(); - HeartBeat(); - } - else - { - try - { - _tcpClient.Close(); - _tcpClient = null; - } - catch (Exception) - { - - } - } - } - } private List<string> heartBeatLogIdList = new List<string>(); /// <summary> @@ -86,325 +26,216 @@ heartBeatLogIdList.Clear(); } - - /// <summary> - /// 鏋勯�犲嚱鏁� - /// </summary> - public Control_TcpClient(string serverIp) + public Socket _socket; + private string host; + private int port; + private static uint _keepAliveTime = 20 * 1000; //鏃犳暟鎹氦浜掓寔缁椂闂�(ms) + private static uint _keepAliveInterval = 500; //鍙戦�佹帰娴嬪寘闂撮殧(ms) + private bool isInit; + //鏋勯�犲嚱鏁� + public Control_TcpClient(string host, int port) { - _ip = serverIp; + this.host = host; + this.port = port; + reconnect = false; } - //TCP杩炴帴 - private bool ConnectToTcp( ) + public void init() { - if (string.IsNullOrEmpty(_ip) ) + if (isInit) { - return false; + return; } - if (_tcpClient == null) - { - _tcpClient = new TcpClient(); - } + isInit = true; + connect(); + readFormSocket(); + reconnect2(); + heartBeat(); + } + //杩炴帴 + private void connect() + { try { - _tcpClient.Connect(IPAddress.Parse(_ip), 8586); - ReceiveMessage();//寮�鍚嚎绋嬶紝涓嶅仠鎺ユ敹娑堟伅 - MainPage.Log($"鎵撳紑tcp client{_ip}:8586"); - isConnected = true; + if (!run) + { + return; + } + MainPage.Log("TcpClient->connect", $"寮�濮嬭繛鎺ワ紝IP:{host}"); + _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + _socket.Connect(host, port); + reconnect = false; + MainPage.Log("TcpClient->connect", $"杩炴帴鎴愬姛锛孖P:{host}"); + + //璁剧疆KeepAlive + _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + byte[] optionValue = new byte[12]; + BitConverter.GetBytes(1).CopyTo(optionValue, 0); + BitConverter.GetBytes(_keepAliveTime).CopyTo(optionValue, 4); + BitConverter.GetBytes(_keepAliveInterval).CopyTo(optionValue, 8); + _socket.IOControl(IOControlCode.KeepAliveValues, optionValue, null); } catch (Exception e) { - MainPage.Log($"鎵撳紑tcp寮傚父锛�"+e.Message); - return false; - } - return true;//杩斿洖杩炴帴鐘舵�� - } - /// <summary> - /// 杩炴帴tcp绾跨▼ - /// </summary> - private Thread connectThread; - - /// <summary> - /// 杩炴帴绾跨▼ - /// </summary> - public void Connect() - { - return; - lock (lockObj) - { - if (isConnected) - { - return; - } - if (connectThread == null) - { - connectThread = new Thread(() => - { - while (Control.Ins.GatewayOnline_Local && !isConnected) - { - if (_tcpClient == null) - { - ConnectToTcp(); - } - else - { - if (!_tcpClient.Connected) - { - try - { - //_tcpClient.ReceiveTimeout = - _tcpClient.Connect(IPAddress.Parse(_ip), 8586); - ReceiveMessage();//寮�鍚嚎绋嬶紝涓嶅仠鎺ユ敹娑堟伅 - isConnected = true; - } - catch (Exception ex) - { - MainPage.Log($"tcp閲嶈繛寮傚父:{ex.Message}"); - } - } - } - Thread.Sleep(1000); - - - } - }); - connectThread.Start(); - } - else - { - if (!isConnected) - { - try - { - connectThread?.Abort(); - } - catch { } - finally - { - connectThread = null; - } - Connect(); - } - } + MainPage.Log("TcpClient->connect", $"杩炴帴澶辫触:{e.Message}"); } } - /// <summary> - /// 閲嶈繛 - /// </summary> - public void Reconect() + //鍙戦�佹暟鎹帴鏀跺疄鐜�,鏂嚎閲嶈繛 + public int CommSend(byte[] buffer, int size) { - if (_tcpClient == null) - { - Connect(); - } - else - { - _tcpClient.Close(); - _tcpClient = null; - Connect(); - } - } - - /// <summary> - /// 鍏抽棴杩炴帴 - /// </summary> - /// <returns></returns> - public bool Close() - { - if (_tcpClient == null) - return true; - _tcpClient.Close(); - _tcpClient = null; - return true; - } - - /// <summary> - /// 鍙戦�佹秷鎭� - /// </summary> - /// <param name="bytes">闇�瑕佸彂閫佺殑瀛楄妭</param> - public void SendMessage(byte[] bytes) - { - return; -#if __IOS__ - -#endif - if (heartBeatLogIdList.Count > 3) - { - try - { - MainPage.Log("蹇冭烦澶氭鏈洖澶嶏紝鏂紑tcp杩炴帴"); - heartBeatLogIdList.Clear(); - isConnected = false; - Reconect(); - return; - }catch (Exception ex) - { - MainPage.Log($"閲嶈繛tcp寮傚父:{ex.Message}"); - } - } + int sendSize = 0; try { - if (_tcpClient == null) + if (_socket.Connected) { - return; + sendSize = _socket.Send(buffer, size, SocketFlags.None); } - if (!_tcpClient.Connected) - { - return; - } - if (_tcpClient.GetStream().CanWrite&& isConnected) - { - _tcpClient.GetStream().Write(bytes, 0, bytes.Length); - } - }catch(Exception ex) - { - MainPage.Log($"tcp瀹㈡埛绔彂閫佹暟鎹紓甯�:{ex.Message}"); - isConnected = false; } + catch (Exception e) + { + MainPage.Log("TcpClient->CommSend", $"鍙戦�佸け璐ワ紝Data:{System.Text.Encoding.UTF8.GetString(buffer)} Exception:{e.Message}"); + //reconnect = true; + } + return sendSize; } - /// <summary> - /// 蹇冭烦鍖呯嚎绋� - /// </summary> - private Thread heartBeatThread; private DateTime heartBeatTime; - public void HeartBeat() + private void heartBeat() { - return; - lock (lockObj) + new Thread(() => { - if (heartBeatThread == null) + while (run) { - MainPage.Log($"蹇冭烦鍖呯嚎绋嬪惎鍔�"); - heartBeatThread = new Thread(() => +#if DEBUG + Thread.Sleep(2000); +#else + Thread.Sleep(3000); +#endif + if (UdpSocket._BusSocket.IsRunning) { - while (isConnected) + if (10 * 1000 < (DateTime.Now - heartBeatTime).TotalMilliseconds) { - if (_tcpClient.Connected && 10 * 1000 < (System.DateTime.Now - heartBeatTime).TotalMilliseconds) - { - string msgId = Control.Ins.msg_id.ToString(); - heartBeatLogIdList.Add(msgId); - var sendJob = new JObject { { "id", Control.Ins.msg_id.ToString() }, { "time_stamp", Utlis.GetTimestamp() } }; - var bodyString = JsonConvert.SerializeObject(sendJob); - - var sendBytes = Control.Ins.ConvertSendBodyData(CommunicationTopic.ct.HeartBeat, bodyString, false); - SendMessage(sendBytes); - heartBeatTime = DateTime.Now; - } - Thread.Sleep(100); + string msgId = Control.Ins.msg_id.ToString(); + heartBeatLogIdList.Add(msgId); + var sendJob = new JObject { { "id", Control.Ins.msg_id.ToString() }, { "time_stamp", Utlis.GetTimestamp() } }; + var bodyString = JsonConvert.SerializeObject(sendJob); + var sendBytes = Control.Ins.ConvertSendBodyData(CommunicationTopic.ct.HeartBeat, bodyString, false); + CommSend(sendBytes, sendBytes.Length); + heartBeatTime = DateTime.Now; } - }); - heartBeatThread.Start(); + } } - else + }) + { IsBackground = true }.Start(); + } + + //鎺ユ敹鏁版嵁绾跨▼,浣跨敤闃诲鏂瑰紡鎺ユ敹鏁版嵁 + private void readFormSocket() + { + new Thread(() => + { + byte[] byteBuffer = new byte[1024 * 5]; + + while (run) { try { - heartBeatThread?.Abort(); - } - catch (Exception ex) - { - MainPage.Log($"鍚姩蹇冭烦绾跨▼锛岄噸鍚嚎绋嬪紓甯�:{ex.Message}"); - } - finally - { - if (heartBeatThread != null) + if (reconnect || !_socket.Connected) { - heartBeatThread = null; + Thread.Sleep(2000); + continue; } - HeartBeat(); + int len = _socket.Receive(byteBuffer, SocketFlags.None); + + if (len == 0) + { + //宸茬粡鏂紑 + reconnect = true; + } + + // 澶勭悊鎺ユ敹鏁版嵁 + var bytes = new byte[len]; + Array.Copy(byteBuffer, 0, bytes, 0, bytes.Length); + LinkMessageDecoder.getInstance().Decoder(bytes, (dd, dd2) => + { + Control.Ins.AnalysisReceiveData(dd, dd2); + }); + } + catch (Exception e) + { + MainPage.Log("TcpClient->ReadFormSocket", $"Exception:{e.Message}"); + reconnect = true; } } - } + }) + { IsBackground = true }.Start(); + } + + Thread reconnectThread; + private void reconnect2() + { + reconnectThread = new Thread(() => + { + while (run) + { + Thread.Sleep(2000); + if (!run) + { + break; + } + if (reconnect) + { + close(); + connect(); + } + } + }); + reconnectThread.IsBackground = true; + reconnectThread.Start(); + } + + /// <summary> + /// 閲婃斁璧勬簮 + /// </summary> + public void Dispose() + { + run = false; + + close(); } /// <summary> - /// 鎺ユ敹鏁版嵁绾跨▼ + /// 鍏抽棴 /// </summary> - private Thread receiveThread; - - private object lockObj = new object(); - - //鎺ユ敹娑堟伅 - public void ReceiveMessage() + private void close() { - lock (lockObj) + try { - if (receiveThread == null) + MainPage.Log("TcpClient->Close", $"Socket 鍏抽棴锛孖P:{host}"); + _socket.Close(); + } + catch { } + } + + + /** + * 鑾峰彇鏁版嵁鐨勫紑濮嬩綅缃� + * @param arrayList 鎺ユ敹鍒扮殑鎵�鏈夋暟鎹� + * @return 鏁版嵁浣嶇殑寮�濮嬬储寮� + */ + int getDataIndex(List<byte> arrayList) + { + var r = (byte)'\r'; + var n = (byte)'\n'; + for (int i = 0; i < arrayList.Count; i++) + { + //鎵惧嚭鏁版嵁鍐呭鍓嶉潰鐨勪袱涓崲琛� + if (3 <= i && arrayList[i - 3] == r && arrayList[i - 2] == n && arrayList[i - 1] == r && arrayList[i] == n) { - receiveThread = new Thread(() => - { - try - { - while (isConnected) - { - if (_tcpClient == null) - { - try - { - receiveThread?.Abort(); - } - catch { } - finally - { - receiveThread = null; - } - return; - } - if (!_tcpClient.Connected) - { - MainPage.Log("tcp瀹㈡埛绔柇寮�浜嗚繛鎺�..."); - isConnected = false; - return; - } - try - { - // 瀹氫箟涓�涓�2M鐨勭紦瀛樺尯锛� - byte[] arrMsgRec = new byte[1024 * 1024 * 2]; - try - { - int size = _tcpClient.GetStream().Read(arrMsgRec, 0, arrMsgRec.Length); - } - catch (Exception ex) - { - isConnected = false; - MainPage.Log($"灞�鍩熺綉tcp鏁版嵁鎺ユ敹寮傚父:{ex.Message}"); - return; - } - var tcpDataString = System.Text.Encoding.UTF8.GetString(arrMsgRec, 0, arrMsgRec.Length); - - - if (!string.IsNullOrEmpty(tcpDataString)) - { - MainPage.Log($"灞�鍩熺綉tcp鏁版嵁鎺ユ敹"); - Control.Ins.ConvertReceiveData(arrMsgRec, null); - - } - } - catch (Exception) { } - } - }catch (Exception ex) - { - MainPage.Log($"tcp ReceiveMessage error :{ex.Message}"); - } - }); - //receiveThread.IsBackground = true; - receiveThread.Start(); - } - else - { - try - { - receiveThread?.Abort(); - } - catch { } - finally - { - receiveThread = null; - ReceiveMessage(); - } + //鍓╀綑鐨勬暟鎹� + return i + 1; } } + return -1; } } -- Gitblit v1.8.0