AsyncSocket.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Net;
  7. using Aitex.Sorter.Common;
  8. using Aitex.Core.RT.Log;
  9. using Aitex.Core.RT.Event;
  10. using System.Configuration;
  11. using MECF.Framework.Common.Equipment;
  12. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Robot
  13. {
  14. public class AsyncSocket : ICommunication, IDisposable
  15. {
  16. public delegate void ErrorHandler(ErrorEventArgs args);
  17. public event ErrorHandler OnErrorHappened;
  18. public delegate void MessageHandler(string message);
  19. public event MessageHandler OnDataChanged;
  20. private static Object _lockerSocket = new Object();
  21. public class ClientStateObject
  22. {
  23. // Client socket.
  24. public Socket workSocket = null;
  25. // Size of receive buffer.
  26. public const int BufferSize = 256;
  27. // Receive buffer.
  28. public byte[] buffer = new byte[BufferSize];
  29. // Received data string.
  30. public StringBuilder sb = new StringBuilder();
  31. }
  32. public string NewLine { get; set; }
  33. public bool EnableLog { get; set; }
  34. public bool IsConnecting
  35. {
  36. get
  37. {
  38. return _isConnecting;
  39. }
  40. }
  41. private Socket _socket;
  42. private string _ip;
  43. private int _port;
  44. private bool _isConnecting;
  45. public bool IsConnected { get { return (_socket != null && _socket.Connected); } }
  46. public AsyncSocket(string address, string newline ="\r")
  47. {
  48. // Connect(address);
  49. _socket = null;
  50. NewLine = newline;
  51. EnableLog = true;
  52. }
  53. ~AsyncSocket()
  54. {
  55. Dispose();
  56. }
  57. public void Connect(string address)
  58. {
  59. try
  60. {
  61. if (_isConnecting)
  62. {
  63. return;
  64. }
  65. _isConnecting = true;
  66. _ip =address.Split(':')[0];
  67. _port =int.Parse(address.Split(':')[1]);
  68. IPAddress ipAddress = IPAddress.Parse(_ip);
  69. IPEndPoint remoteEP = new IPEndPoint(ipAddress, _port);
  70. //Dispose current socket and create a TCP/IP socket.
  71. Dispose();
  72. if(_socket == null)
  73. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  74. // Connect to the remote endpoint.
  75. _socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), _socket);
  76. }
  77. catch (Exception e)
  78. {
  79. LOG.Write(e);
  80. throw new Exception(e.ToString());
  81. }
  82. }
  83. private void ConnectCallback(IAsyncResult ar)
  84. {
  85. try
  86. {
  87. // Retrieve the socket from the state object.
  88. Socket client = (Socket)ar.AsyncState;
  89. if (client == null || !client.Connected || _socket == null || !_socket.Connected)
  90. {
  91. _isConnecting = false;
  92. return;
  93. }
  94. // Complete the connection.
  95. client.EndConnect(ar);
  96. EV.PostMessage(ModuleName.Robot.ToString(), EventEnum.TCPConnSucess, _ip, _port.ToString());
  97. // Receive the response from the remote device.
  98. Receive(_socket);
  99. _isConnecting = false;
  100. }
  101. catch(Exception e)
  102. {
  103. LOG.Write(e);
  104. string reason = string.Format("Communication {0}:{1:D} {2}.", _ip, _port, e.Message);
  105. LOG.Error(reason);
  106. // EV.PostMessage(UnitName.Transfer.ToString(), EventEnum.RobotCommandFailed, reason);
  107. OnErrorHappened(new ErrorEventArgs(reason));
  108. _isConnecting = false;
  109. }
  110. }
  111. private void Receive(Socket client)
  112. {
  113. try
  114. {
  115. // Create the state object.
  116. ClientStateObject state = new ClientStateObject();
  117. state.workSocket = client;
  118. // Begin receiving the data from the remote device.
  119. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  120. }
  121. catch (Exception e)
  122. {
  123. LOG.Write(e);
  124. string reason = string.Format("TCP连接发生错误:{0}", e.Message);
  125. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  126. OnErrorHappened(new ErrorEventArgs(reason));
  127. }
  128. }
  129. private void ReceiveCallback(IAsyncResult ar)
  130. {
  131. try
  132. {
  133. if (!IsConnected) { return; }
  134. // Retrieve the state object and the client socket
  135. // from the asynchronous state object.
  136. ClientStateObject state = (ClientStateObject)ar.AsyncState;
  137. Socket client = state.workSocket;
  138. // Read data from the remote device.
  139. int bytesRead = client.EndReceive(ar);
  140. if (bytesRead > 0)
  141. {
  142. // There might be more data, so store the data received so far.
  143. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  144. if (state.sb.Length > NewLine.Length)
  145. {
  146. if (state.sb.ToString().Substring(state.sb.Length - NewLine.Length).Equals(NewLine))
  147. {
  148. string msg =state.sb.ToString();
  149. string raw = msg;
  150. if (raw.Contains("\r"))
  151. raw = raw.Replace("\r", "\\r");
  152. if (raw.Contains("\n"))
  153. raw = raw.Replace("\n", "\\n");
  154. if(EnableLog)
  155. LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, raw));
  156. OnDataChanged(state.sb.ToString());
  157. state.sb.Clear();
  158. }
  159. }
  160. // Get the rest of the data.
  161. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  162. }
  163. }
  164. catch (Exception ex)
  165. {
  166. LOG.Write(ex);
  167. string reason = string.Format("TCP Socket recevice data failed:{0}", ex.Message);
  168. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  169. OnErrorHappened(new ErrorEventArgs(reason));
  170. }
  171. }
  172. public bool Write(string data)
  173. {
  174. try
  175. {
  176. lock (_lockerSocket)
  177. {
  178. // Convert the string data to byte data using ASCII encoding.
  179. byte[] byteData = Encoding.ASCII.GetBytes(data);
  180. _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  181. if (data.Contains("\r"))
  182. data = data.Replace("\r", "\\r");
  183. if (data.Contains("\n"))
  184. data = data.Replace("\n", "\\n");
  185. if(EnableLog)
  186. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, data));
  187. }
  188. return true;
  189. }
  190. catch (Exception ex)
  191. {
  192. LOG.Write(ex);
  193. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}. failed", _ip, _port, data));
  194. string reason = string.Format("Send command failed:{0}", ex.Message);
  195. OnErrorHappened(new ErrorEventArgs(reason));
  196. }
  197. return false;
  198. }
  199. private void SendCallback(IAsyncResult ar)
  200. {
  201. try
  202. {
  203. // Retrieve the socket from the state object.
  204. Socket client = (Socket)ar.AsyncState;
  205. // Complete sending the data to the remote device.
  206. int bytesSent = client.EndSend(ar);
  207. }
  208. catch (Exception ex)
  209. {
  210. LOG.Write(ex);
  211. string reason = string.Format("Send command failed:{0}", ex.Message);
  212. OnErrorHappened(new ErrorEventArgs(reason));
  213. }
  214. }
  215. /// <summary>
  216. /// 释放资源(Dispose)
  217. /// </summary>
  218. public void Dispose()
  219. {
  220. try
  221. {
  222. _isConnecting = false;
  223. if (_socket != null)
  224. {
  225. if (IsConnected)
  226. {
  227. _socket.Shutdown(SocketShutdown.Both);
  228. }
  229. _socket.Close();
  230. _socket.Dispose();
  231. _socket = null;
  232. }
  233. }
  234. catch (Exception ex)
  235. {
  236. LOG.Write(ex);
  237. string reason = string.Format("释放socket资源失败:{0}", ex.Message);
  238. OnErrorHappened(new ErrorEventArgs(reason));
  239. }
  240. }
  241. }
  242. }