AsyncSocket.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. using System.Threading;
  13. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Robot
  14. {
  15. public enum DataType
  16. {
  17. Ascii,
  18. Byte
  19. }
  20. public class AsyncSocket : ICommunication, IDisposable
  21. {
  22. public delegate void ErrorHandler(ErrorEventArgs args);
  23. public event ErrorHandler OnErrorHappened;
  24. public delegate void MessageHandler(string message);
  25. public event MessageHandler OnDataChanged;
  26. public delegate void BufferDataHander(byte[] data);
  27. public event BufferDataHander OnBufferDataReceived;
  28. public delegate void ConnectHandler();
  29. public event ConnectHandler OnConnect;
  30. private static Object _locker = new Object();
  31. public class ClientStateObject
  32. {
  33. // Client socket.
  34. public Socket workSocket = null;
  35. // Size of receive buffer.
  36. public const int BufferSize = 8192;
  37. // Receive buffer.
  38. public byte[] buffer = new byte[BufferSize];
  39. // Received data string.
  40. public StringBuilder sb = new StringBuilder();
  41. }
  42. private string _newLine { get; set; }
  43. private Socket _socket;
  44. private string _ip;
  45. private int _port;
  46. private DataType _dataType;
  47. private bool _supportReconnect = false;
  48. private int _reconnectInterval = 3000;
  49. private object _reconnectLocker = new object();
  50. private Thread _reconnectThread = null;
  51. public bool IsConnected { get { return (_socket != null && _socket.Connected); } }
  52. public AsyncSocket(string address, string newline ="\r",DataType dataType=DataType.Ascii,bool supportReconnect=false)
  53. {
  54. // Connect(address);
  55. _socket = null;
  56. _newLine = newline;
  57. _supportReconnect = supportReconnect;
  58. _dataType = dataType;
  59. }
  60. ~AsyncSocket()
  61. {
  62. Dispose();
  63. }
  64. public void Connect(string address)
  65. {
  66. _ip =address.Split(':')[0];
  67. _port =int.Parse(address.Split(':')[1]);
  68. try
  69. {
  70. Connect();
  71. }
  72. catch
  73. {
  74. }
  75. }
  76. /// <summary>
  77. /// 连接
  78. /// </summary>
  79. /// <exception cref="Exception"></exception>
  80. private void Connect()
  81. {
  82. try
  83. {
  84. IPAddress ipAddress = IPAddress.Parse(_ip);
  85. IPEndPoint remoteEP = new IPEndPoint(ipAddress, _port);
  86. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  87. _socket.ReceiveTimeout = 2000;
  88. _socket.SendTimeout = 2000;
  89. // Connect to the remote endpoint.
  90. _socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), _socket);
  91. }
  92. catch (Exception e)
  93. {
  94. if (!_supportReconnect)
  95. {
  96. throw new Exception(e.ToString());
  97. }
  98. else
  99. {
  100. StartReconnectThread();
  101. }
  102. }
  103. }
  104. /// <summary>
  105. /// 启动重新连接线程
  106. /// </summary>
  107. private void StartReconnectThread()
  108. {
  109. lock (_reconnectLocker)
  110. {
  111. if (_reconnectThread==null)
  112. {
  113. _reconnectThread = new Thread(ReConnectThread);
  114. _reconnectThread.IsBackground = true;
  115. _reconnectThread.Start();
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// 重新连接线程
  121. /// </summary>
  122. private void ReConnectThread()
  123. {
  124. //休眠一定时间后再连接
  125. Thread.Sleep(_reconnectInterval);
  126. try
  127. {
  128. Connect();
  129. }
  130. catch
  131. {
  132. }
  133. _reconnectThread = null;
  134. }
  135. /// <summary>
  136. /// 连接回调函数
  137. /// </summary>
  138. /// <param name="ar"></param>
  139. private void ConnectCallback(IAsyncResult ar)
  140. {
  141. try
  142. {
  143. // Retrieve the socket from the state object.
  144. Socket client = (Socket)ar.AsyncState;
  145. // Complete the connection.
  146. client.EndConnect(ar);
  147. if(OnConnect!=null)
  148. {
  149. OnConnect();
  150. }
  151. // Receive the response from the remote device.
  152. Receive(_socket);
  153. }
  154. catch(Exception e)
  155. {
  156. string reason = string.Format("Communication {0}:{1:D} {2}.", _ip, _port, e.Message);
  157. OnErrorHappened(new ErrorEventArgs(reason));
  158. if (_supportReconnect)
  159. {
  160. StartReconnectThread();
  161. }
  162. }
  163. }
  164. /// <summary>
  165. /// 异步接收数据
  166. /// </summary>
  167. /// <param name="client"></param>
  168. private void Receive(Socket client)
  169. {
  170. try
  171. {
  172. // Create the state object.
  173. ClientStateObject state = new ClientStateObject();
  174. state.workSocket = client;
  175. // Begin receiving the data from the remote device.
  176. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  177. }
  178. catch (Exception e)
  179. {
  180. string reason = string.Format("TCP connect failed:{0}", e.Message);
  181. OnErrorHappened(new ErrorEventArgs(reason));
  182. if (_supportReconnect)
  183. {
  184. StartReconnectThread();
  185. }
  186. }
  187. }
  188. /// <summary>
  189. /// 接收数据回调数据
  190. /// </summary>
  191. /// <param name="ar"></param>
  192. private void ReceiveCallback(IAsyncResult ar)
  193. {
  194. try
  195. {
  196. if (!IsConnected) { return; }
  197. // Retrieve the state object and the client socket
  198. // from the asynchronous state object.
  199. ClientStateObject state = (ClientStateObject)ar.AsyncState;
  200. Socket client = state.workSocket;
  201. // Read data from the remote device.
  202. int bytesRead = client.EndReceive(ar);
  203. if (bytesRead > 0)
  204. {
  205. // There might be more data, so store the data received so far.
  206. if (_dataType == DataType.Ascii)
  207. {
  208. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  209. if (state.sb.Length > _newLine.Length)
  210. {
  211. if (state.sb.ToString().Substring(state.sb.Length - _newLine.Length).Equals(_newLine))
  212. {
  213. string msg = state.sb.ToString();
  214. if (OnDataChanged != null)
  215. {
  216. OnDataChanged(state.sb.ToString());
  217. }
  218. state.sb.Clear();
  219. }
  220. }
  221. }
  222. else
  223. {
  224. if(OnBufferDataReceived!=null)
  225. {
  226. OnBufferDataReceived(state.buffer);
  227. }
  228. }
  229. // Get the rest of the data.
  230. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  231. }
  232. }
  233. catch (Exception ex)
  234. {
  235. LOG.WriteExeption(ex);
  236. string reason = string.Format("TCP Socket recevice data failed:{0}", ex.Message);
  237. OnErrorHappened(new ErrorEventArgs(reason));
  238. if (_supportReconnect)
  239. {
  240. StartReconnectThread();
  241. }
  242. }
  243. }
  244. /// <summary>
  245. /// 写数据
  246. /// </summary>
  247. /// <param name="data"></param>
  248. /// <returns></returns>
  249. public bool Write(string data)
  250. {
  251. if(_socket==null||!_socket.Connected)
  252. {
  253. return false;
  254. }
  255. try
  256. {
  257. lock (_locker)
  258. {
  259. // Convert the string data to byte data using ASCII encoding.
  260. byte[] byteData = Encoding.ASCII.GetBytes(data);
  261. _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  262. }
  263. return true;
  264. }
  265. catch (Exception ex)
  266. {
  267. LOG.WriteExeption(ex);
  268. string reason = string.Format("Send command failed:{0}", ex.Message);
  269. OnErrorHappened(new ErrorEventArgs(reason));
  270. if (_supportReconnect)
  271. {
  272. StartReconnectThread();
  273. }
  274. }
  275. return false;
  276. }
  277. /// <summary>
  278. /// 写入二进制数据
  279. /// </summary>
  280. /// <param name="byteData"></param>
  281. /// <returns></returns>
  282. public bool Write(byte[] byteData)
  283. {
  284. if (_socket == null || !_socket.Connected)
  285. {
  286. return false;
  287. }
  288. try
  289. {
  290. lock (_locker)
  291. {
  292. _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  293. }
  294. return true;
  295. }
  296. catch (Exception ex)
  297. {
  298. LOG.WriteExeption(ex);
  299. string reason = string.Format("Send command failed:{0}", ex.Message);
  300. OnErrorHappened(new ErrorEventArgs(reason));
  301. if(_supportReconnect)
  302. {
  303. StartReconnectThread();
  304. }
  305. }
  306. return false;
  307. }
  308. /// <summary>
  309. /// 发送数据回调函数
  310. /// </summary>
  311. /// <param name="ar"></param>
  312. private void SendCallback(IAsyncResult ar)
  313. {
  314. try
  315. {
  316. // Retrieve the socket from the state object.
  317. Socket client = (Socket)ar.AsyncState;
  318. // Complete sending the data to the remote device.
  319. int bytesSent = client.EndSend(ar);
  320. }
  321. catch (Exception ex)
  322. {
  323. LOG.WriteExeption(ex);
  324. string reason = string.Format("Send command failed:{0}", ex.Message);
  325. OnErrorHappened(new ErrorEventArgs(reason));
  326. if (_supportReconnect)
  327. {
  328. StartReconnectThread();
  329. }
  330. }
  331. }
  332. /// <summary>
  333. /// 释放资源(Dispose)
  334. /// </summary>
  335. public void Dispose()
  336. {
  337. try
  338. {
  339. if (_socket != null)
  340. {
  341. if (IsConnected)
  342. {
  343. _socket.Shutdown(SocketShutdown.Both);
  344. }
  345. _socket.Close();
  346. _socket.Dispose();
  347. _socket = null;
  348. _supportReconnect = false;
  349. }
  350. }
  351. catch (Exception ex)
  352. {
  353. LOG.WriteExeption(ex);
  354. string reason = string.Format("释放socket资源失败:{0}", ex.Message);
  355. OnErrorHappened(new ErrorEventArgs(reason));
  356. }
  357. }
  358. }
  359. }