RobotTcpClient.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using TeamAAS.Robot.Enums;
  9. using TeamAAS.Communication.Enums;
  10. namespace TeamAAS.Robot.Core
  11. {
  12. /// <summary>
  13. /// 机器人 TCP 通讯封装类。
  14. /// 支持 Client/Server 双模式、结束符分割、请求-响应、断线重连。
  15. /// </summary>
  16. public class RobotTcpClient : IDisposable
  17. {
  18. private readonly string _ip;
  19. private readonly int _port;
  20. private readonly TCPConnectType _connectType;
  21. private readonly Terminator _terminator;
  22. private readonly DataEncoding _dataEncoding;
  23. private TcpClient _tcpClient;
  24. private TcpListener _tcpListener;
  25. private TcpClient _serverSession;
  26. private NetworkStream _serverStream;
  27. private readonly AutoResetEvent _receiveEvent = new AutoResetEvent(false);
  28. private byte[] _receivedData;
  29. private readonly object _sendLock = new object();
  30. private readonly object _sessionLock = new object();
  31. private Task _reconnectTask;
  32. private CancellationTokenSource _reconnectCts;
  33. private bool _isDisposed;
  34. private string _terminatorString;
  35. private byte[] _terminatorBytes;
  36. public bool IsConnected
  37. {
  38. get
  39. {
  40. if (_connectType == TCPConnectType.Client)
  41. return _tcpClient?.Connected ?? false;
  42. else
  43. return _serverSession?.Connected ?? false;
  44. }
  45. }
  46. public RobotTcpClient(
  47. string ip,
  48. int port,
  49. TCPConnectType connectType,
  50. Terminator terminator,
  51. DataEncoding dataEncoding)
  52. {
  53. _ip = ip;
  54. _port = port;
  55. _connectType = connectType;
  56. _terminator = terminator;
  57. _dataEncoding = dataEncoding;
  58. _terminatorString = terminator switch
  59. {
  60. Terminator.CR => "\r",
  61. Terminator.LF => "\n",
  62. Terminator.CRLF => "\r\n",
  63. _ => "\r\n"
  64. };
  65. _terminatorBytes = GetEncoding().GetBytes(_terminatorString);
  66. }
  67. public void Connect()
  68. {
  69. if (_connectType == TCPConnectType.Client)
  70. ConnectClient();
  71. else
  72. ConnectServer();
  73. }
  74. public async Task ConnectAsync()
  75. {
  76. if (_connectType == TCPConnectType.Client)
  77. {
  78. await ConnectClientAsync();
  79. }
  80. else
  81. {
  82. ConnectServer();
  83. }
  84. }
  85. private void ConnectClient()
  86. {
  87. _tcpClient = new TcpClient();
  88. _tcpClient.Connect(IPAddress.Parse(_ip), _port);
  89. StartReconnectLoop();
  90. StartReceiveLoop();
  91. OnConnected?.Invoke(null);
  92. }
  93. private async Task ConnectClientAsync()
  94. {
  95. _tcpClient = new TcpClient();
  96. await _tcpClient.ConnectAsync(IPAddress.Parse(_ip), _port);
  97. StartReconnectLoop();
  98. StartReceiveLoop();
  99. OnConnected?.Invoke(null);
  100. }
  101. private void ConnectServer()
  102. {
  103. _tcpListener = new TcpListener(IPAddress.Any, _port);
  104. _tcpListener.Start();
  105. AcceptClientLoop();
  106. }
  107. private async void AcceptClientLoop()
  108. {
  109. while (!_isDisposed && _tcpListener != null)
  110. {
  111. try
  112. {
  113. var client = await _tcpListener.AcceptTcpClientAsync();
  114. lock (_sessionLock)
  115. {
  116. _serverSession = client;
  117. _serverStream = client.GetStream();
  118. }
  119. StartServerReceiveLoop(client);
  120. OnConnected?.Invoke(null);
  121. }
  122. catch (ObjectDisposedException) { break; }
  123. catch (Exception)
  124. {
  125. if (!_isDisposed)
  126. await Task.Delay(1000);
  127. }
  128. }
  129. }
  130. private void StartReceiveLoop()
  131. {
  132. var stream = _tcpClient.GetStream();
  133. Task.Run(() => ReceiveDataLoop(stream));
  134. }
  135. private void StartServerReceiveLoop(TcpClient client)
  136. {
  137. var stream = client.GetStream();
  138. Task.Run(() => ReceiveDataLoop(stream));
  139. }
  140. private async void ReceiveDataLoop(NetworkStream stream)
  141. {
  142. byte[] buffer = new byte[4096];
  143. MemoryStream ms = new MemoryStream();
  144. while (!_isDisposed)
  145. {
  146. try
  147. {
  148. int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
  149. if (bytesRead == 0) break;
  150. ms.Write(buffer, 0, bytesRead);
  151. while (ContainsTerminator(ms))
  152. {
  153. byte[] message = ExtractMessage(ms);
  154. ProcessReceivedData(message);
  155. }
  156. }
  157. catch (IOException)
  158. {
  159. break;
  160. }
  161. catch (Exception)
  162. {
  163. if (!_isDisposed)
  164. await Task.Delay(100);
  165. else
  166. break;
  167. }
  168. }
  169. if (_connectType == TCPConnectType.Client)
  170. {
  171. OnDisconnected?.Invoke(null);
  172. }
  173. else
  174. {
  175. lock (_sessionLock)
  176. {
  177. if (_serverSession != null && _serverSession == GetCurrentSession())
  178. {
  179. _serverSession = null;
  180. _serverStream = null;
  181. }
  182. }
  183. OnDisconnected?.Invoke(null);
  184. }
  185. }
  186. private TcpClient GetCurrentSession()
  187. {
  188. return _serverSession;
  189. }
  190. private bool ContainsTerminator(MemoryStream ms)
  191. {
  192. if (ms.Length < _terminatorBytes.Length) return false;
  193. byte[] data = ms.ToArray();
  194. for (int i = 0; i <= data.Length - _terminatorBytes.Length; i++)
  195. {
  196. bool match = true;
  197. for (int j = 0; j < _terminatorBytes.Length; j++)
  198. {
  199. if (data[i + j] != _terminatorBytes[j])
  200. {
  201. match = false;
  202. break;
  203. }
  204. }
  205. if (match) return true;
  206. }
  207. return false;
  208. }
  209. private byte[] ExtractMessage(MemoryStream ms)
  210. {
  211. byte[] data = ms.ToArray();
  212. int endIndex = -1;
  213. for (int i = 0; i <= data.Length - _terminatorBytes.Length; i++)
  214. {
  215. bool match = true;
  216. for (int j = 0; j < _terminatorBytes.Length; j++)
  217. {
  218. if (data[i + j] != _terminatorBytes[j])
  219. {
  220. match = false;
  221. break;
  222. }
  223. }
  224. if (match)
  225. {
  226. endIndex = i + _terminatorBytes.Length;
  227. break;
  228. }
  229. }
  230. byte[] message;
  231. if (endIndex > 0)
  232. {
  233. message = new byte[endIndex];
  234. Array.Copy(data, message, endIndex);
  235. ms.Position = 0;
  236. ms.SetLength(0);
  237. if (endIndex < data.Length)
  238. {
  239. ms.Write(data, endIndex, data.Length - endIndex);
  240. }
  241. }
  242. else
  243. {
  244. message = data;
  245. ms.Position = 0;
  246. ms.SetLength(0);
  247. }
  248. return message;
  249. }
  250. private void ProcessReceivedData(byte[] data)
  251. {
  252. _receivedData = data;
  253. OnReceived?.Invoke(data);
  254. _receiveEvent.Set();
  255. }
  256. private void StartReconnectLoop()
  257. {
  258. _reconnectCts = new CancellationTokenSource();
  259. _reconnectTask = Task.Run(async () =>
  260. {
  261. while (!_reconnectCts.Token.IsCancellationRequested)
  262. {
  263. await Task.Delay(1000, _reconnectCts.Token);
  264. if (_reconnectCts.Token.IsCancellationRequested) break;
  265. if (_connectType == TCPConnectType.Client && !IsConnected)
  266. {
  267. try
  268. {
  269. _tcpClient?.Close();
  270. _tcpClient = new TcpClient();
  271. _tcpClient.Connect(IPAddress.Parse(_ip), _port);
  272. StartReceiveLoop();
  273. }
  274. catch { }
  275. }
  276. }
  277. });
  278. }
  279. public void Disconnect()
  280. {
  281. _isDisposed = true;
  282. _reconnectCts?.Cancel();
  283. _tcpClient?.Close();
  284. _tcpListener?.Stop();
  285. _serverSession?.Close();
  286. }
  287. public string SendAndReceive(string message, int timeoutMs = 5000)
  288. {
  289. byte[] data = SendAndReceiveBytes(GetEncoding().GetBytes(message + _terminatorString), timeoutMs);
  290. return GetEncoding().GetString(data).TrimEnd('\r', '\n');
  291. }
  292. public async Task<string> SendAndReceiveAsync(string message, int timeoutMs = 5000)
  293. {
  294. byte[] data = await SendAndReceiveBytesAsync(GetEncoding().GetBytes(message + _terminatorString), timeoutMs);
  295. return GetEncoding().GetString(data).TrimEnd('\r', '\n');
  296. }
  297. private byte[] SendAndReceiveBytes(byte[] data, int timeoutMs)
  298. {
  299. lock (_sendLock)
  300. {
  301. SendBytesInternal(data);
  302. OnSent?.Invoke(GetEncoding().GetString(data));
  303. if (!_receiveEvent.WaitOne(timeoutMs))
  304. throw new TimeoutException($"等待机器人响应超时({timeoutMs}ms):已发送 \"{GetEncoding().GetString(data).Trim()}\"");
  305. return _receivedData ?? Array.Empty<byte>();
  306. }
  307. }
  308. private async Task<byte[]> SendAndReceiveBytesAsync(byte[] data, int timeoutMs)
  309. {
  310. await Task.Run(() =>
  311. {
  312. lock (_sendLock)
  313. {
  314. SendBytesInternal(data);
  315. OnSent?.Invoke(GetEncoding().GetString(data));
  316. if (!_receiveEvent.WaitOne(timeoutMs))
  317. throw new TimeoutException($"等待机器人响应超时({timeoutMs}ms):已发送 \"{GetEncoding().GetString(data).Trim()}\"");
  318. }
  319. });
  320. return _receivedData ?? Array.Empty<byte>();
  321. }
  322. public void Send(string message)
  323. {
  324. byte[] data = GetEncoding().GetBytes(message + _terminatorString);
  325. SendBytesInternal(data);
  326. OnSent?.Invoke(message);
  327. }
  328. public async Task SendAsync(string message)
  329. {
  330. byte[] data = GetEncoding().GetBytes(message + _terminatorString);
  331. await SendBytesInternalAsync(data);
  332. OnSent?.Invoke(message);
  333. }
  334. private void SendBytesInternal(byte[] data)
  335. {
  336. if (_connectType == TCPConnectType.Client)
  337. {
  338. if (_tcpClient != null && _tcpClient.Connected)
  339. {
  340. var stream = _tcpClient.GetStream();
  341. stream.Write(data, 0, data.Length);
  342. stream.Flush();
  343. }
  344. }
  345. else
  346. {
  347. lock (_sessionLock)
  348. {
  349. if (_serverStream != null && _serverSession != null && _serverSession.Connected)
  350. {
  351. _serverStream.Write(data, 0, data.Length);
  352. _serverStream.Flush();
  353. }
  354. }
  355. }
  356. }
  357. private async Task SendBytesInternalAsync(byte[] data)
  358. {
  359. if (_connectType == TCPConnectType.Client)
  360. {
  361. if (_tcpClient != null && _tcpClient.Connected)
  362. {
  363. var stream = _tcpClient.GetStream();
  364. await stream.WriteAsync(data, 0, data.Length);
  365. await stream.FlushAsync();
  366. }
  367. }
  368. else
  369. {
  370. lock (_sessionLock)
  371. {
  372. if (_serverStream != null && _serverSession != null && _serverSession.Connected)
  373. {
  374. _serverStream.Write(data, 0, data.Length);
  375. _serverStream.Flush();
  376. }
  377. }
  378. }
  379. }
  380. public Encoding GetEncoding()
  381. {
  382. return _dataEncoding switch
  383. {
  384. DataEncoding.ASCII => Encoding.ASCII,
  385. DataEncoding.UTF7 => Encoding.UTF7,
  386. DataEncoding.UTF8 => Encoding.UTF8,
  387. DataEncoding.UTF32 => Encoding.UTF32,
  388. DataEncoding.Unicode => Encoding.Unicode,
  389. _ => Encoding.Default
  390. };
  391. }
  392. public void Dispose()
  393. {
  394. Disconnect();
  395. _tcpClient?.Dispose();
  396. _serverSession?.Dispose();
  397. _serverStream?.Dispose();
  398. _receiveEvent.Dispose();
  399. _reconnectCts?.Dispose();
  400. }
  401. public event Action<byte[]> OnConnected;
  402. public event Action<byte[]> OnDisconnected;
  403. public event Action<byte[]> OnReceived;
  404. public event Action<string> OnSent;
  405. }
  406. }