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