AsyncSocket.cs 8.8 KB

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