AsyncSocket.cs 8.3 KB

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