AsyncSocket.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 int _bufferSize = 256;
  34. public bool IsConnected { get { return (_socket != null && _socket.Connected); } }
  35. //public bool IsConnected { get { return (_socket != null && IsSocketConnected(_socket)); } }
  36. private bool IsSocketConnected(Socket client)
  37. {
  38. try
  39. {
  40. byte[] tmp = new byte[] { 0x0, 0x0, 0x0 };
  41. //int a= newclient.Receive(tmp);
  42. int a = client.Send(tmp);
  43. if (a == 1)
  44. return true;
  45. else
  46. return false;
  47. }
  48. catch (SocketException e)
  49. {
  50. LOG.Write(e);
  51. return false;
  52. }
  53. }
  54. public AsyncSocket(string address, string newline = "\r")
  55. {
  56. // Connect(address);
  57. _socket = null;
  58. NewLine = newline;
  59. }
  60. public AsyncSocket(string address, int bufferSize, string newline = "\r")
  61. {
  62. _socket = null;
  63. NewLine = newline;
  64. _bufferSize = bufferSize;
  65. }
  66. ~AsyncSocket()
  67. {
  68. Dispose();
  69. }
  70. public void Connect(string address)
  71. {
  72. try
  73. {
  74. _ip = address.Split(':')[0];
  75. _port = int.Parse(address.Split(':')[1]);
  76. IPAddress ipAddress = IPAddress.Parse(_ip);
  77. IPEndPoint remoteEP = new IPEndPoint(ipAddress, _port);
  78. //Dispose current socket and create a TCP/IP socket.
  79. Dispose();
  80. if (_socket == null)
  81. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  82. // Connect to the remote endpoint.
  83. _socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), _socket);
  84. }
  85. catch (Exception e)
  86. {
  87. LOG.Write(e);
  88. throw new Exception(e.ToString());
  89. }
  90. }
  91. private void ConnectCallback(IAsyncResult ar)
  92. {
  93. try
  94. {
  95. // Retrieve the socket from the state object.
  96. Socket client = (Socket)ar.AsyncState;
  97. // Complete the connection.
  98. client.EndConnect(ar);
  99. EV.PostMessage(ModuleName.Robot.ToString(), EventEnum.TCPConnSucess, _ip, _port.ToString());
  100. // Receive the response from the remote device.
  101. Receive(_socket);
  102. }
  103. catch (Exception e)
  104. {
  105. LOG.Write(e);
  106. string reason = string.Format("Communication {0}:{1:D} {2}.", _ip, _port, e.Message);
  107. LOG.Error(reason);
  108. // EV.PostMessage(UnitName.Transfer.ToString(), EventEnum.RobotCommandFailed, reason);
  109. OnErrorHappened(new ErrorEventArgs(reason));
  110. }
  111. }
  112. private void Receive(Socket client)
  113. {
  114. try
  115. {
  116. // Create the state object.
  117. ClientStateObject state = new ClientStateObject();
  118. state.workSocket = client;
  119. // Begin receiving the data from the remote device.
  120. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  121. }
  122. catch (Exception e)
  123. {
  124. LOG.Write(e);
  125. string reason = string.Format("TCP连接发生错误:{0}", e.Message);
  126. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  127. OnErrorHappened(new ErrorEventArgs(reason));
  128. }
  129. }
  130. private void ReceiveCallback(IAsyncResult ar)
  131. {
  132. try
  133. {
  134. if (!IsConnected) { return; }
  135. // Retrieve the state object and the client socket
  136. // from the asynchronous state object.
  137. ClientStateObject state = (ClientStateObject)ar.AsyncState;
  138. Socket client = state.workSocket;
  139. // Read data from the remote device.
  140. int bytesRead = client.EndReceive(ar);
  141. if (bytesRead > 0)
  142. {
  143. // There might be more data, so store the data received so far.
  144. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  145. if (state.sb.Length > NewLine.Length)
  146. {
  147. if (state.sb.ToString().Substring(state.sb.Length - NewLine.Length).Equals(NewLine))
  148. {
  149. string msg = state.sb.ToString();
  150. LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, msg.TrimEnd('\n').TrimEnd('\r')));
  151. OnDataChanged(state.sb.ToString());
  152. state.sb.Clear();
  153. }
  154. }
  155. // Get the rest of the data.
  156. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  157. }
  158. }
  159. catch (Exception ex)
  160. {
  161. LOG.Write(ex);
  162. string reason = string.Format("TCP Socket recevice data failed:{0}", ex.Message);
  163. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  164. OnErrorHappened(new ErrorEventArgs(reason));
  165. }
  166. }
  167. public bool Write(string data)
  168. {
  169. try
  170. {
  171. lock (_locker)
  172. {
  173. // Convert the string data to byte data using ASCII encoding.
  174. byte[] byteData = Encoding.ASCII.GetBytes(data);
  175. _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  176. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, data));
  177. }
  178. return true;
  179. }
  180. catch (Exception ex)
  181. {
  182. LOG.Write(ex);
  183. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}. failed", _ip, _port, data));
  184. string reason = string.Format("Send command failed:{0}", ex.Message);
  185. OnErrorHappened(new ErrorEventArgs(reason));
  186. }
  187. return false;
  188. }
  189. private void SendCallback(IAsyncResult ar)
  190. {
  191. try
  192. {
  193. // Retrieve the socket from the state object.
  194. Socket client = (Socket)ar.AsyncState;
  195. // Complete sending the data to the remote device.
  196. int bytesSent = client.EndSend(ar);
  197. }
  198. catch (Exception ex)
  199. {
  200. LOG.Write(ex);
  201. string reason = string.Format("Send command failed:{0}", ex.Message);
  202. OnErrorHappened(new ErrorEventArgs(reason));
  203. }
  204. }
  205. /// <summary>
  206. /// 释放资源(Dispose)
  207. /// </summary>
  208. public void Dispose()
  209. {
  210. try
  211. {
  212. if (_socket != null)
  213. {
  214. if (IsConnected)
  215. {
  216. _socket.Shutdown(SocketShutdown.Both);
  217. }
  218. _socket.Close();
  219. _socket.Dispose();
  220. _socket = null;
  221. }
  222. }
  223. catch (Exception ex)
  224. {
  225. LOG.Write(ex);
  226. string reason = string.Format("release socket failed:{0}", ex.Message);
  227. OnErrorHappened(new ErrorEventArgs(reason));
  228. }
  229. }
  230. }
  231. //public class AsyncSocket : ICommunication, IDisposable
  232. //{
  233. // public delegate void ErrorHandler(ErrorEventArgs args);
  234. // public event ErrorHandler OnErrorHappened;
  235. // public delegate void MessageHandler(string message);
  236. // public event MessageHandler OnDataChanged;
  237. // private static Object _locker = new Object();
  238. // public class ClientStateObject
  239. // {
  240. // // Client socket.
  241. // public Socket workSocket = null;
  242. // // Size of receive buffer.
  243. // public static int BufferSize = 256;
  244. // // Receive buffer.
  245. // public byte[] buffer = new byte[BufferSize];
  246. // // Received data string.
  247. // public StringBuilder sb = new StringBuilder();
  248. // public ClientStateObject(int bufferSize = 256)
  249. // {
  250. // BufferSize = bufferSize;
  251. // buffer = new byte[bufferSize];
  252. // }
  253. // }
  254. // public string NewLine { get; set; }
  255. // public bool NeedLog { get; set; } = true;
  256. // private Socket _socket;
  257. // private string _ip;
  258. // private int _port;
  259. // private string _address;
  260. // private int _bufferSize = 256;
  261. // public bool IsConnected { get { return (_socket != null && _socket.Connected); } } //&& !_socket.Poll(100, SelectMode.SelectRead)); } }
  262. // public bool IsHstConnected { get { return (_socket != null && IsSocketConnected(_socket)); } }
  263. // private bool IsSocketConnected(Socket client)
  264. // {
  265. // try
  266. // {
  267. // byte[] tmp = new byte[] { 0x0};
  268. // //int a= newclient.Receive(tmp);
  269. // int a = client.Send(tmp);
  270. // if (a == 1)
  271. // return true;
  272. // else
  273. // return false;
  274. // }
  275. // catch (SocketException e)
  276. // {
  277. // LOG.Write(e.Message);
  278. // return false;
  279. // }
  280. // }
  281. // public AsyncSocket(string address, string newline ="\r")
  282. // {
  283. // // Connect(address);
  284. // _socket = null;
  285. // NewLine = newline;
  286. // _address = address;
  287. // }
  288. // public AsyncSocket(string address, int bufferSize, string newline ="\r")
  289. // {
  290. // _socket = null;
  291. // NewLine = newline;
  292. // _address = address;
  293. // _bufferSize = bufferSize;
  294. // }
  295. // ~AsyncSocket()
  296. // {
  297. // Dispose();
  298. // }
  299. // public void Connect(string address)
  300. // {
  301. // try
  302. // {
  303. // _ip =address.Split(':')[0];
  304. // _port =int.Parse(address.Split(':')[1]);
  305. // IPAddress ipAddress = IPAddress.Parse(_ip);
  306. // IPEndPoint remoteEP = new IPEndPoint(ipAddress, _port);
  307. // lock (_locker)
  308. // {
  309. // //Dispose current socket and create a TCP/IP socket.
  310. // Dispose();
  311. // if(_socket == null)
  312. // _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  313. // // Connect to the remote endpoint.
  314. // _socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), _socket);
  315. // }
  316. // }
  317. // catch (Exception e)
  318. // {
  319. // LOG.Write(e);
  320. // throw new Exception(e.ToString());
  321. // }
  322. // }
  323. // private void ConnectCallback(IAsyncResult ar)
  324. // {
  325. // try
  326. // {
  327. // // Retrieve the socket from the state object.
  328. // Socket client = (Socket)ar.AsyncState;
  329. // // Complete the connection.
  330. // client.EndConnect(ar);
  331. // EV.PostMessage(ModuleName.Robot.ToString(), EventEnum.TCPConnSucess, _ip, _port.ToString());
  332. // // Receive the response from the remote device.
  333. // Receive(_socket);
  334. // }
  335. // catch(Exception e)
  336. // {
  337. // LOG.Write(e);
  338. // string reason = string.Format("Communication {0}:{1:D} {2}.", _ip, _port, e.Message);
  339. // LOG.Error(reason);
  340. // // EV.PostMessage(UnitName.Transfer.ToString(), EventEnum.RobotCommandFailed, reason);
  341. // //OnErrorHappened(new ErrorEventArgs(reason));
  342. // Thread.Sleep(1000);
  343. // Connect(_address);
  344. // }
  345. // }
  346. // private void Receive(Socket client)
  347. // {
  348. // try
  349. // {
  350. // // Create the state object.
  351. // ClientStateObject state = new ClientStateObject(_bufferSize);
  352. // state.workSocket = client;
  353. // // Begin receiving the data from the remote device.
  354. // client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  355. // }
  356. // catch (Exception e)
  357. // {
  358. // LOG.Write(e);
  359. // string reason = string.Format("TCP connection error:{0}", e.Message);
  360. // LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  361. // OnErrorHappened(new ErrorEventArgs(reason));
  362. // }
  363. // }
  364. // private void ReceiveCallback(IAsyncResult ar)
  365. // {
  366. // try
  367. // {
  368. // if (!IsConnected) { return; }
  369. // // Retrieve the state object and the client socket
  370. // // from the asynchronous state object.
  371. // ClientStateObject state = (ClientStateObject)ar.AsyncState;
  372. // Socket client = state.workSocket;
  373. // // Read data from the remote device.
  374. // int bytesRead = client.EndReceive(ar);
  375. // if (bytesRead > 0)
  376. // {
  377. // // There might be more data, so store the data received so far.
  378. // state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  379. // if (state.sb.Length > NewLine.Length)
  380. // {
  381. // if (state.sb.ToString().Substring(state.sb.Length - NewLine.Length).Equals(NewLine))
  382. // {
  383. // string msg =state.sb.ToString();
  384. // if(NeedLog)
  385. // LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, msg.TrimEnd('\n').TrimEnd('\r')));
  386. // OnDataChanged(state.sb.ToString());
  387. // state.sb.Clear();
  388. // }
  389. // }
  390. // // Get the rest of the data.
  391. // client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  392. // }
  393. // }
  394. // catch (Exception ex)
  395. // {
  396. // LOG.Write(ex);
  397. // string reason = string.Format("TCP Socket recevice data failed:{0}", ex.Message);
  398. // LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  399. // OnErrorHappened(new ErrorEventArgs(reason));
  400. // }
  401. // }
  402. // public bool Write(string data)
  403. // {
  404. // try
  405. // {
  406. // lock (_locker)
  407. // {
  408. // // Convert the string data to byte data using ASCII encoding.
  409. // byte[] byteData = Encoding.ASCII.GetBytes(data);
  410. // _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  411. // LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, data));
  412. // }
  413. // return true;
  414. // }
  415. // catch (Exception ex)
  416. // {
  417. // LOG.Write(ex);
  418. // LOG.Info(string.Format("Communication {0}:{1:D} Send {2}. failed", _ip, _port, data));
  419. // string reason = string.Format("Send command failed:{0}", ex.Message);
  420. // OnErrorHappened(new ErrorEventArgs(reason));
  421. // }
  422. // return false;
  423. // }
  424. // private void SendCallback(IAsyncResult ar)
  425. // {
  426. // try
  427. // {
  428. // // Retrieve the socket from the state object.
  429. // Socket client = (Socket)ar.AsyncState;
  430. // // Complete sending the data to the remote device.
  431. // int bytesSent = client.EndSend(ar);
  432. // }
  433. // catch (Exception ex)
  434. // {
  435. // LOG.Write(ex);
  436. // string reason = string.Format("Send command failed:{0}", ex.Message);
  437. // OnErrorHappened(new ErrorEventArgs(reason));
  438. // }
  439. // }
  440. // /// <summary>
  441. // /// 释放资源(Dispose)
  442. // /// </summary>
  443. // public void Dispose()
  444. // {
  445. // try
  446. // {
  447. // if (_socket != null)
  448. // {
  449. // if (IsConnected)
  450. // {
  451. // _socket.Shutdown(SocketShutdown.Both);
  452. // }
  453. // _socket.Close();
  454. // _socket.Dispose();
  455. // _socket = null;
  456. // }
  457. // }
  458. // catch (Exception ex)
  459. // {
  460. // LOG.Write(ex);
  461. // string reason = string.Format("释放socket资源失败:{0}", ex.Message);
  462. // OnErrorHappened(new ErrorEventArgs(reason));
  463. // }
  464. // }
  465. //}
  466. }