AsynSocketClient.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Threading;
  9. using Aitex.Core.RT.Event;
  10. using Aitex.Core.RT.Log;
  11. using MECF.Framework.Common.Equipment;
  12. namespace MECF.Framework.Common.Communications
  13. {
  14. public class AsynSocketClient : IDisposable
  15. {
  16. public delegate void ErrorHandler(TCPErrorEventArgs args);
  17. public event ErrorHandler OnErrorHappened;
  18. public delegate void MessageHandler(string message);
  19. public event MessageHandler OnDataChanged;
  20. public delegate void BinaryMessageHandler(byte[] message);
  21. public event BinaryMessageHandler OnBinaryDataChanged;
  22. private static Object _locker = new Object();
  23. public class ClientStateObject
  24. {
  25. // Client socket.
  26. public Socket workSocket = null;
  27. // Size of receive buffer.
  28. public static int BufferSize = 256;
  29. // Receive buffer.
  30. public byte[] buffer = new byte[BufferSize];
  31. // Received data string.
  32. public StringBuilder sb = new StringBuilder();
  33. public ClientStateObject(int bufferSize = 256)
  34. {
  35. BufferSize = bufferSize;
  36. buffer = new byte[bufferSize];
  37. }
  38. }
  39. public string NewLine { get; set; }
  40. public bool NeedLog { get; set; } = true;
  41. private Socket _socket;
  42. private string _ip;
  43. private int _port;
  44. private string _address;
  45. private int _bufferSize = 256;
  46. private bool _isEndConnect = false;
  47. private ProtocolType _protocolType = ProtocolType.Unknown;
  48. public bool IsConnected { get { return (_socket != null && _socket.Connected && _isEndConnect); } } //&& !_socket.Poll(100, SelectMode.SelectRead)); } }
  49. public bool IsHstConnected { get { return (_socket != null && IsSocketConnected(_socket)); } }
  50. private bool IsSocketConnected(Socket client)
  51. {
  52. try
  53. {
  54. byte[] tmp = new byte[] { 0x0 };
  55. //int a= newclient.Receive(tmp);
  56. int a = client.Send(tmp);
  57. if (a == 1)
  58. return true;
  59. else
  60. return false;
  61. }
  62. catch (SocketException e)
  63. {
  64. LOG.Write(e.Message);
  65. return false;
  66. }
  67. }
  68. bool _isAsciiMode;
  69. public AsynSocketClient(string address, bool isAsciiMode, string newline = "\r", ProtocolType protocolType = ProtocolType.Tcp)
  70. {
  71. // Connect(address);
  72. _socket = null;
  73. NewLine = newline;
  74. _address = address;
  75. _isAsciiMode = isAsciiMode;
  76. _protocolType = protocolType;
  77. }
  78. public AsynSocketClient(string address, int bufferSize, string newline = "\r")
  79. {
  80. _socket = null;
  81. NewLine = newline;
  82. _address = address;
  83. _bufferSize = bufferSize;
  84. }
  85. ~AsynSocketClient()
  86. {
  87. Dispose();
  88. }
  89. public void Connect()
  90. {
  91. try
  92. {
  93. if (_address==null)
  94. {
  95. return;
  96. }
  97. _ip = _address.Split(':')[0];
  98. _port = int.Parse(_address.Split(':')[1]);
  99. IPAddress ipAddress = IPAddress.Parse(_ip);
  100. IPEndPoint remoteEP = new IPEndPoint(ipAddress, _port);
  101. lock (_locker)
  102. {
  103. _isEndConnect = false;
  104. //Dispose current socket and create a TCP/IP socket.
  105. Dispose();
  106. if (NeedLog)
  107. {
  108. LOG.Info(string.Format("Start new socket of {0}.", _address));
  109. }
  110. if (_socket == null)
  111. _socket = new Socket(AddressFamily.InterNetwork, _protocolType == ProtocolType.Udp ? SocketType.Dgram : SocketType.Stream, _protocolType != ProtocolType.Unknown ? _protocolType : ProtocolType.Tcp);
  112. // Connect to the remote endpoint.
  113. _socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), _socket);
  114. }
  115. }
  116. catch (Exception e)
  117. {
  118. LOG.Write(e);
  119. throw new Exception(e.ToString());
  120. }
  121. }
  122. private void ConnectCallback(IAsyncResult ar)
  123. {
  124. try
  125. {
  126. if (NeedLog)
  127. {
  128. LOG.Info(string.Format("ConnectCallback {0}", _address));
  129. }
  130. // Retrieve the socket from the state object.
  131. Socket client = (Socket)ar.AsyncState;
  132. // Complete the connection.
  133. if (!client.Connected)
  134. return;
  135. client.EndConnect(ar);
  136. _isEndConnect = true;
  137. if (NeedLog)
  138. {
  139. LOG.Info(string.Format("EndConnect"));
  140. }
  141. EV.PostMessage(ModuleName.Robot.ToString(), EventEnum.TCPConnSucess, _ip, _port.ToString());
  142. // Receive the response from the remote device.
  143. Receive(_socket);
  144. }
  145. catch (Exception ex)
  146. {
  147. LOG.Write(ex);
  148. string reason = string.Format("Communication {0}:{1:D} {2}.", _ip, _port, ex);
  149. LOG.Error(reason);
  150. // EV.PostMessage(UnitName.Transfer.ToString(), EventEnum.RobotCommandFailed, reason);
  151. //OnErrorHappened(new TCPErrorEventArgs(reason));
  152. Thread.Sleep(1000);
  153. Connect();
  154. }
  155. }
  156. private void Receive(Socket client)
  157. {
  158. try
  159. {
  160. // Create the state object.
  161. ClientStateObject state = new ClientStateObject(_bufferSize);
  162. state.workSocket = client;
  163. // Begin receiving the data from the remote device.
  164. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  165. }
  166. catch (Exception e)
  167. {
  168. LOG.Write(e);
  169. string reason = string.Format("TCP连接发生错误:{0}", e.Message);
  170. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  171. OnErrorHappened(new TCPErrorEventArgs(reason));
  172. }
  173. }
  174. private void ReceiveCallback(IAsyncResult ar)
  175. {
  176. try
  177. {
  178. if (!IsConnected) { return; }
  179. // Retrieve the state object and the client socket
  180. // from the asynchronous state object.
  181. ClientStateObject state = (ClientStateObject)ar.AsyncState;
  182. Socket client = state.workSocket;
  183. if (client == null || !client.Connected)
  184. return;
  185. // Read data from the remote device.
  186. int bytesRead = client.EndReceive(ar);
  187. if (bytesRead > 0)
  188. {
  189. // There might be more data, so store the data received so far.
  190. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  191. string receiveMessage = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
  192. if (!_isAsciiMode)
  193. {
  194. //string msg = state.sb.ToString();
  195. //if (NeedLog)
  196. // LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, msg.TrimEnd('\n').TrimEnd('\r')));
  197. byte[] recvBuff = new byte[bytesRead];
  198. for(int i = 0; i < bytesRead; i++)
  199. {
  200. recvBuff[i] = state.buffer[i];
  201. }
  202. if (NeedLog)
  203. {
  204. LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, string.Join(" ", Array.ConvertAll(recvBuff, x => x.ToString("X2")))));
  205. LOG.Info(string.Format("Communication {0}:{1:D} receive {2} in ASCII.", _ip, _port, Encoding.ASCII.GetString(recvBuff)));
  206. }
  207. OnBinaryDataChanged(recvBuff);
  208. state.sb.Clear();
  209. }
  210. else if (state.sb.Length > NewLine.Length)
  211. {
  212. if (state.sb.ToString().Substring(state.sb.Length - NewLine.Length).Equals(NewLine))
  213. {
  214. string msg = state.sb.ToString();
  215. if (NeedLog)
  216. {
  217. LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, msg.TrimEnd('\n').TrimEnd('\r')));
  218. LOG.Info(string.Format("Communication {0}:{1:D} receive {2}. in BIN", _ip, _port, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))));
  219. }
  220. OnDataChanged(state.sb.ToString());
  221. state.sb.Clear();
  222. }
  223. }
  224. // Get the rest of the data.
  225. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  226. }
  227. }
  228. catch (Exception ex)
  229. {
  230. LOG.Write(ex);
  231. string reason = string.Format("TCP Socket recevice data failed:{0}", ex.Message);
  232. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  233. OnErrorHappened(new TCPErrorEventArgs(reason));
  234. }
  235. }
  236. public bool Write(string data)
  237. {
  238. try
  239. {
  240. lock (_locker)
  241. {
  242. // Convert the string data to byte data using ASCII encoding.
  243. byte[] byteData = Encoding.ASCII.GetBytes(data);
  244. _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  245. if (NeedLog)
  246. {
  247. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, data));
  248. string dataString = string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(data), x => x.ToString("X2")));
  249. LOG.Info(string.Format("Communication {0}:{1:D} Send {2} in Bin.", _ip, _port, dataString));
  250. }
  251. }
  252. return true;
  253. }
  254. catch (Exception ex)
  255. {
  256. LOG.Write(ex);
  257. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}. failed", _ip, _port, data));
  258. string reason = string.Format("Send command failed:{0}", ex.Message);
  259. OnErrorHappened(new TCPErrorEventArgs(reason));
  260. }
  261. return false;
  262. }
  263. public bool Write(byte[] byteData)
  264. {
  265. try
  266. {
  267. lock (_locker)
  268. {
  269. // Convert the string data to byte data using ASCII encoding.
  270. //byte[] byteData = Encoding.ASCII.GetBytes(data);
  271. _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  272. if (NeedLog)
  273. {
  274. string dataString = string.Join(" ", Array.ConvertAll(byteData, x => x.ToString("X2")));
  275. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, dataString));
  276. LOG.Info(string.Format("Communication {0}:{1:D} Send {2} in ASCII.", _ip, _port, Encoding.ASCII.GetString(byteData)));
  277. }
  278. }
  279. return true;
  280. }
  281. catch (Exception ex)
  282. {
  283. LOG.Write(ex);
  284. string dataString = string.Join(" ", Array.ConvertAll(byteData, x => x.ToString("X2")));
  285. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}. failed", _ip, _port, dataString));
  286. string reason = string.Format("Send command failed:{0}", ex.Message);
  287. OnErrorHappened(new TCPErrorEventArgs(reason));
  288. }
  289. return false;
  290. }
  291. private void SendCallback(IAsyncResult ar)
  292. {
  293. try
  294. {
  295. // Retrieve the socket from the state object.
  296. Socket client = (Socket)ar.AsyncState;
  297. // Complete sending the data to the remote device.
  298. int bytesSent = client.EndSend(ar);
  299. }
  300. catch (Exception ex)
  301. {
  302. LOG.Write(ex);
  303. string reason = string.Format("Send command failed:{0}", ex.Message);
  304. OnErrorHappened(new TCPErrorEventArgs(reason));
  305. }
  306. }
  307. /// <summary>
  308. /// 释放资源(Dispose)
  309. /// </summary>
  310. public void Dispose()
  311. {
  312. try
  313. {
  314. if (_socket != null)
  315. {
  316. if (NeedLog)
  317. {
  318. LOG.Info(string.Format("Dispose current socket of {0}", _address));
  319. }
  320. if (IsConnected)
  321. {
  322. _socket.Shutdown(SocketShutdown.Both);
  323. }
  324. _socket.Close();
  325. _socket.Dispose();
  326. _socket = null;
  327. }
  328. }
  329. catch (Exception ex)
  330. {
  331. LOG.Write(ex);
  332. string reason = string.Format("释放socket资源失败:{0}", ex.Message);
  333. OnErrorHappened(new TCPErrorEventArgs(reason));
  334. }
  335. }
  336. }
  337. public class TCPErrorEventArgs : EventArgs
  338. {
  339. public readonly string Reason;
  340. public readonly string Code;
  341. public TCPErrorEventArgs(string reason, string code = "")
  342. {
  343. Reason = reason;
  344. Code = code;
  345. }
  346. }
  347. }