AsyncSocket.cs 8.4 KB

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