using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace IMCS.CCS.DeviceProtocol { public class DeviceSocket { private Socket ClientSocket; private string ip; int port; public DeviceSocket(string _ip, int _port) { ip = _ip; port = _port; } private bool _ison = false; public bool IsOn { get { return _ison; } set { } } public void DeviceInit() { try { ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ClientSocket.Connect(ip, port); } catch (Exception ex) { IMCS.CCS.Log.Instance.WriteLogAdd($"53-->{ex.Message}"); //IsOn = true; IsOn = false; } // byte[] bt = Encoding.UTF8.GetBytes("Hello"); // ClientSocket.Send(bt); } public void DeviceState() { System.Timers.Timer timer = new System.Timers.Timer(); timer.Elapsed += Timer_Elapsed; timer.Interval = 3000; timer.Start(); } private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { // if (ClientSocket != null && ClientSocket.Connected) { // ClientSocket.Send(Encoding.UTF8.GetBytes("\r")); IsOn = true; } } catch (Exception ex) { IMCS.CCS.Log.Instance.WriteLogAdd($"85-->{ex.Message}"); IsOn = false; //ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //ClientSocket.Connect("192.168.0.11", 1100); //if (!ClientSocket.Connected) { ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { ClientSocket.Connect(ip, port); } catch { Log.Instance.WriteLogAdd($"{ip}-重新连接失败"); } } } finally { } } public void ReceiveSocket() { byte[] by = new byte[1024]; while (true) { if (ClientSocket != null) /*&& IsOn*/ { int leng = 0; try { leng = ClientSocket.Receive(by); } catch (Exception ex) { IMCS.CCS.Log.Instance.WriteLogAdd($"123-->{ex.Message}"); } } } } public void DeviceStart() { Task.Factory.StartNew(() => { while (true) { byte[] by = new byte[1024]; if (ClientSocket != null) /*&& IsOn*/ { int leng = 0; try { leng = ClientSocket.Receive(by); } catch (Exception ex) { IMCS.CCS.Log.Instance.WriteLogAdd($"154-->{ex.Message}"); } } } }); } public void DeviceSend(object ob) { string SendValue; try { SendValue = ob.ToString(); if (ClientSocket.Connected) { ClientSocket.Close(); this.DeviceInit(); } ClientSocket.Send(Encoding.ASCII.GetBytes(ob.ToString())); } catch (Exception ex) { this.DeviceInit(); System.Threading.Thread.Sleep(1000); SendValue = ob.ToString(); ClientSocket.Send(Encoding.ASCII.GetBytes(ob.ToString())); IMCS.CCS.Log.Instance.WriteLogAdd($"179-->{ex.Message}"); } } } }