AsynSocketClient.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Threading;
  9. using Aitex.Core.RT.Event;
  10. using Aitex.Core.RT.Log;
  11. using MECF.Framework.Common.Equipment;
  12. namespace MECF.Framework.Common.Communications
  13. {
  14. public class AsynSocketClient : IDisposable
  15. {
  16. public delegate void ErrorHandler(TCPErrorEventArgs args);
  17. public event ErrorHandler OnErrorHappened;
  18. public delegate void MessageHandler(string message);
  19. public event MessageHandler OnDataChanged;
  20. public delegate void BinaryMessageHandler(byte[] message);
  21. public event BinaryMessageHandler OnBinaryDataChanged;
  22. private static Object _locker = new Object();
  23. public class ClientStateObject
  24. {
  25. // Client socket.
  26. public Socket workSocket = null;
  27. // Size of receive buffer.
  28. public static int BufferSize = 256;
  29. // Receive buffer.
  30. public byte[] buffer = new byte[BufferSize];
  31. // Received data string.
  32. public StringBuilder sb = new StringBuilder();
  33. public ClientStateObject(int bufferSize = 256)
  34. {
  35. BufferSize = bufferSize;
  36. buffer = new byte[bufferSize];
  37. }
  38. }
  39. public string NewLine { get; set; }
  40. public bool NeedLog { get; set; } = true;
  41. private Socket _socket;
  42. private string _ip;
  43. private int _port;
  44. private string _address;
  45. private int _bufferSize = 256;
  46. private bool _isEndConnect = false;
  47. public bool IsConnected { get { return (_socket != null && _socket.Connected && _isEndConnect); } } //&& !_socket.Poll(100, SelectMode.SelectRead)); } }
  48. public bool IsHstConnected { get { return (_socket != null && IsSocketConnected(_socket)); } }
  49. private bool IsSocketConnected(Socket client)
  50. {
  51. try
  52. {
  53. byte[] tmp = new byte[] { 0x0 };
  54. //int a= newclient.Receive(tmp);
  55. int a = client.Send(tmp);
  56. if (a == 1)
  57. return true;
  58. else
  59. return false;
  60. }
  61. catch (SocketException e)
  62. {
  63. LOG.Write(e.Message);
  64. return false;
  65. }
  66. }
  67. bool _isAsciiMode;
  68. public AsynSocketClient(string address, bool isAsciiMode, string newline = "\r")
  69. {
  70. // Connect(address);
  71. _socket = null;
  72. NewLine = newline;
  73. _address = address;
  74. _isAsciiMode = isAsciiMode;
  75. }
  76. public AsynSocketClient(string address, int bufferSize, string newline = "\r")
  77. {
  78. _socket = null;
  79. NewLine = newline;
  80. _address = address;
  81. _bufferSize = bufferSize;
  82. }
  83. ~AsynSocketClient()
  84. {
  85. Dispose();
  86. }
  87. public void Connect()
  88. {
  89. try
  90. {
  91. _ip = _address.Split(':')[0];
  92. _port = int.Parse(_address.Split(':')[1]);
  93. IPAddress ipAddress = IPAddress.Parse(_ip);
  94. IPEndPoint remoteEP = new IPEndPoint(ipAddress, _port);
  95. lock (_locker)
  96. {
  97. _isEndConnect = false;
  98. //Dispose current socket and create a TCP/IP socket.
  99. Dispose();
  100. if (NeedLog)
  101. {
  102. LOG.Info(string.Format("Start new socket of {0}.", _address));
  103. }
  104. if (_socket == null)
  105. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  106. // Connect to the remote endpoint.
  107. _socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), _socket);
  108. }
  109. }
  110. catch (Exception e)
  111. {
  112. LOG.Write(e);
  113. throw new Exception(e.ToString());
  114. }
  115. }
  116. private void ConnectCallback(IAsyncResult ar)
  117. {
  118. try
  119. {
  120. if (NeedLog)
  121. {
  122. LOG.Info(string.Format("ConnectCallback {0}", _address));
  123. }
  124. // Retrieve the socket from the state object.
  125. Socket client = (Socket)ar.AsyncState;
  126. // Complete the connection.
  127. if (!client.Connected)
  128. return;
  129. client.EndConnect(ar);
  130. _isEndConnect = true;
  131. if (NeedLog)
  132. {
  133. LOG.Info(string.Format("EndConnect"));
  134. }
  135. EV.PostMessage(ModuleName.Robot.ToString(), EventEnum.TCPConnSucess, _ip, _port.ToString());
  136. // Receive the response from the remote device.
  137. Receive(_socket);
  138. }
  139. catch (Exception ex)
  140. {
  141. LOG.Write(ex);
  142. string reason = string.Format("Communication {0}:{1:D} {2}.", _ip, _port, ex);
  143. LOG.Error(reason);
  144. // EV.PostMessage(UnitName.Transfer.ToString(), EventEnum.RobotCommandFailed, reason);
  145. //OnErrorHappened(new TCPErrorEventArgs(reason));
  146. Thread.Sleep(1000);
  147. Connect();
  148. }
  149. }
  150. private void Receive(Socket client)
  151. {
  152. try
  153. {
  154. // Create the state object.
  155. ClientStateObject state = new ClientStateObject(_bufferSize);
  156. state.workSocket = client;
  157. // Begin receiving the data from the remote device.
  158. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  159. }
  160. catch (Exception e)
  161. {
  162. LOG.Write(e);
  163. string reason = string.Format("TCP连接发生错误:{0}", e.Message);
  164. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  165. OnErrorHappened(new TCPErrorEventArgs(reason));
  166. }
  167. }
  168. private void ReceiveCallback(IAsyncResult ar)
  169. {
  170. try
  171. {
  172. if (!IsConnected) { return; }
  173. // Retrieve the state object and the client socket
  174. // from the asynchronous state object.
  175. ClientStateObject state = (ClientStateObject)ar.AsyncState;
  176. Socket client = state.workSocket;
  177. if (client == null || !client.Connected)
  178. return;
  179. // Read data from the remote device.
  180. int bytesRead = client.EndReceive(ar);
  181. if (bytesRead > 0)
  182. {
  183. // There might be more data, so store the data received so far.
  184. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  185. string receiveMessage = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
  186. if (!_isAsciiMode)
  187. {
  188. //string msg = state.sb.ToString();
  189. //if (NeedLog)
  190. // LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, msg.TrimEnd('\n').TrimEnd('\r')));
  191. byte[] recvBuff = new byte[bytesRead];
  192. for(int i = 0; i < bytesRead; i++)
  193. {
  194. recvBuff[i] = state.buffer[i];
  195. }
  196. if (NeedLog)
  197. {
  198. LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, string.Join(" ", Array.ConvertAll(recvBuff, x => x.ToString("X2")))));
  199. LOG.Info(string.Format("Communication {0}:{1:D} receive {2} in ASCII.", _ip, _port, Encoding.ASCII.GetString(recvBuff)));
  200. }
  201. OnBinaryDataChanged(recvBuff);
  202. state.sb.Clear();
  203. }
  204. else if (state.sb.Length > NewLine.Length)
  205. {
  206. if (state.sb.ToString().Substring(state.sb.Length - NewLine.Length).Equals(NewLine))
  207. {
  208. string msg = state.sb.ToString();
  209. if (NeedLog)
  210. {
  211. LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, msg.TrimEnd('\n').TrimEnd('\r')));
  212. LOG.Info(string.Format("Communication {0}:{1:D} receive {2}. in BIN", _ip, _port, string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(msg), x => x.ToString("X2")))));
  213. }
  214. OnDataChanged(state.sb.ToString());
  215. state.sb.Clear();
  216. }
  217. }
  218. // Get the rest of the data.
  219. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  220. }
  221. }
  222. catch (Exception ex)
  223. {
  224. LOG.Write(ex);
  225. string reason = string.Format("TCP Socket recevice data failed:{0}", ex.Message);
  226. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  227. OnErrorHappened(new TCPErrorEventArgs(reason));
  228. }
  229. }
  230. public bool Write(string data)
  231. {
  232. try
  233. {
  234. lock (_locker)
  235. {
  236. // Convert the string data to byte data using ASCII encoding.
  237. byte[] byteData = Encoding.ASCII.GetBytes(data);
  238. _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  239. if (NeedLog)
  240. {
  241. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, data));
  242. string dataString = string.Join(" ", Array.ConvertAll(Encoding.ASCII.GetBytes(data), x => x.ToString("X2")));
  243. LOG.Info(string.Format("Communication {0}:{1:D} Send {2} in Bin.", _ip, _port, dataString));
  244. }
  245. }
  246. return true;
  247. }
  248. catch (Exception ex)
  249. {
  250. LOG.Write(ex);
  251. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}. failed", _ip, _port, data));
  252. string reason = string.Format("Send command failed:{0}", ex.Message);
  253. OnErrorHappened(new TCPErrorEventArgs(reason));
  254. }
  255. return false;
  256. }
  257. public bool Write(byte[] byteData)
  258. {
  259. try
  260. {
  261. lock (_locker)
  262. {
  263. // Convert the string data to byte data using ASCII encoding.
  264. //byte[] byteData = Encoding.ASCII.GetBytes(data);
  265. _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  266. if (NeedLog)
  267. {
  268. string dataString = string.Join(" ", Array.ConvertAll(byteData, x => x.ToString("X2")));
  269. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, dataString));
  270. LOG.Info(string.Format("Communication {0}:{1:D} Send {2} in ASCII.", _ip, _port, Encoding.ASCII.GetString(byteData)));
  271. }
  272. }
  273. return true;
  274. }
  275. catch (Exception ex)
  276. {
  277. LOG.Write(ex);
  278. string dataString = string.Join(" ", Array.ConvertAll(byteData, x => x.ToString("X2")));
  279. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}. failed", _ip, _port, dataString));
  280. string reason = string.Format("Send command failed:{0}", ex.Message);
  281. OnErrorHappened(new TCPErrorEventArgs(reason));
  282. }
  283. return false;
  284. }
  285. private void SendCallback(IAsyncResult ar)
  286. {
  287. try
  288. {
  289. // Retrieve the socket from the state object.
  290. Socket client = (Socket)ar.AsyncState;
  291. // Complete sending the data to the remote device.
  292. int bytesSent = client.EndSend(ar);
  293. }
  294. catch (Exception ex)
  295. {
  296. LOG.Write(ex);
  297. string reason = string.Format("Send command failed:{0}", ex.Message);
  298. OnErrorHappened(new TCPErrorEventArgs(reason));
  299. }
  300. }
  301. /// <summary>
  302. /// 释放资源(Dispose)
  303. /// </summary>
  304. public void Dispose()
  305. {
  306. try
  307. {
  308. if (_socket != null)
  309. {
  310. if (NeedLog)
  311. {
  312. LOG.Info(string.Format("Dispose current socket of {0}", _address));
  313. }
  314. if (IsConnected)
  315. {
  316. _socket.Shutdown(SocketShutdown.Both);
  317. }
  318. _socket.Close();
  319. _socket.Dispose();
  320. _socket = null;
  321. }
  322. }
  323. catch (Exception ex)
  324. {
  325. LOG.Write(ex);
  326. string reason = string.Format("释放socket资源失败:{0}", ex.Message);
  327. OnErrorHappened(new TCPErrorEventArgs(reason));
  328. }
  329. }
  330. }
  331. public class TCPErrorEventArgs : EventArgs
  332. {
  333. public readonly string Reason;
  334. public readonly string Code;
  335. public TCPErrorEventArgs(string reason, string code = "")
  336. {
  337. Reason = reason;
  338. Code = code;
  339. }
  340. }
  341. }