AsynSocketClient.cs 14 KB

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