JetTcpClient.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. using Aitex.Core.RT.Log;
  2. using Aitex.Core.Utilities;
  3. using DocumentFormat.OpenXml.ExtendedProperties;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MECF.Framework.Common.Net
  13. {
  14. public class JetTcpClient
  15. {
  16. #region 内部变量
  17. private string _ip="127.0.0.1";
  18. private int _port = 9600;
  19. private bool _connected = false;
  20. protected int _reconnectInterval = 500;
  21. protected DateTime _connectTime = DateTime.Now;
  22. private int _connectTimeout = 2000;
  23. private int _receiveTimeout = 1000;
  24. private int _sendTimeout = 1000;
  25. private object _connectLocker=new object();
  26. private object _reconnectLocker = new object();
  27. private object _sendLocker = new object();
  28. private object _receiveLocker = new object();
  29. private object _closeLocker = new object();
  30. private AutoResetEvent _connectAutoResetEvent=new AutoResetEvent(false);
  31. private Socket _socket = null;
  32. private bool _logEnabled;
  33. private string _name;
  34. private eEvent _eventId;
  35. #endregion
  36. #region 属性
  37. /// <summary>
  38. /// 重连间隔时长
  39. /// </summary>
  40. public int ReconnectInterval { set { _reconnectInterval = value; } }
  41. /// <summary>
  42. /// 连接超时时长
  43. /// </summary>
  44. public int ConnectTimeout { set { _connectTimeout = value; } }
  45. /// <summary>
  46. /// 接收超时时长
  47. /// </summary>
  48. public int ReceiveTimeout { set { _receiveTimeout = value; } }
  49. /// <summary>
  50. /// 发送超时时长
  51. /// </summary>
  52. public int SendTimeout { set { _sendTimeout = value; } }
  53. /// <summary>
  54. /// 连接状态
  55. /// </summary>
  56. public bool Connected { get { return _connected; } }
  57. /// <summary>
  58. /// 是否启用LOG
  59. /// </summary>
  60. public bool LogEnabled { set { _logEnabled=value; }}
  61. /// <summary>
  62. /// 名称
  63. /// </summary>
  64. public string Name { set { _name=value; } }
  65. /// <summary>
  66. /// 事件Id
  67. /// </summary>
  68. public eEvent EventId { set { _eventId = value; } }
  69. #endregion
  70. /// <summary>
  71. /// 构造函数
  72. /// </summary>
  73. /// <param name="ip"></param>
  74. /// <param name="port"></param>
  75. public JetTcpClient(string ip,int port)
  76. {
  77. _ip= ip;
  78. _port= port;
  79. }
  80. /// <summary>
  81. /// 连接
  82. /// </summary>
  83. public NetResult Connect()
  84. {
  85. if (_connected)
  86. {
  87. return NetResult.CreateSuccessResult();
  88. }
  89. if(!Monitor.TryEnter(_connectLocker,_connectTimeout))
  90. {
  91. return NetResult.CreateFailedResult(NetErrorCode.LockerOccupied);
  92. }
  93. _connectTime = DateTime.Now;
  94. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  95. _socket.ReceiveTimeout = _receiveTimeout;
  96. _socket.SendTimeout=_sendTimeout;
  97. NetStateObject stateObject=new NetStateObject();
  98. stateObject.Socket = _socket;
  99. stateObject.AutoResetEvent = _connectAutoResetEvent;
  100. EndPoint localEndpoint = _socket.LocalEndPoint;
  101. if(IPAddress.TryParse(_ip,out IPAddress ipAddress))
  102. {
  103. try
  104. {
  105. _socket.BeginConnect(new IPEndPoint(ipAddress, _port), new AsyncCallback(ConnectCallBack), stateObject);
  106. }
  107. catch(Exception ex)
  108. {
  109. stateObject.Dispose();
  110. stateObject = null;
  111. ConnectFailedBusiness();
  112. Monitor.Exit(_connectLocker);
  113. return NetResult.CreateFailedResult((int)NetErrorCode.InnerException, ex.Message);
  114. }
  115. if (!_connectAutoResetEvent.WaitOne(_connectTimeout))
  116. {
  117. stateObject.Dispose();
  118. stateObject = null;
  119. ConnectFailedBusiness();
  120. Monitor.Exit(_connectLocker);
  121. return NetResult.CreateFailedResult(NetErrorCode.ConnectTimeout);
  122. }
  123. LOG.WriteLog(eEvent.EV_DEVICE_INFO, "System", $"Connect {_ip}:{_port} Success,local {localEndpoint}");
  124. _connected = true;
  125. stateObject.Dispose();
  126. stateObject = null;
  127. Monitor.Exit(_connectLocker);
  128. return NetResult.CreateSuccessResult();
  129. }
  130. else
  131. {
  132. stateObject.Dispose();
  133. stateObject = null;
  134. ConnectFailedBusiness();
  135. Monitor.Exit(_connectLocker);
  136. return NetResult.CreateFailedResult(NetErrorCode.InvalidIpAddress);
  137. }
  138. }
  139. /// <summary>
  140. /// 中止
  141. /// </summary>
  142. public void Stop()
  143. {
  144. CloseSocket();
  145. }
  146. /// <summary>
  147. /// 连接失败后处理
  148. /// </summary>
  149. /// <param name="stateObject"></param>
  150. private void ConnectFailedBusiness()
  151. {
  152. _connectAutoResetEvent.Reset();
  153. CloseSocket();
  154. }
  155. /// <summary>
  156. /// 关闭Socket
  157. /// </summary>
  158. private void CloseSocket()
  159. {
  160. if (Monitor.TryEnter(_closeLocker, 10))
  161. {
  162. if (_socket != null)
  163. {
  164. try
  165. {
  166. _socket.Shutdown(SocketShutdown.Both);
  167. }
  168. catch
  169. {
  170. }
  171. try
  172. {
  173. _socket.Close();
  174. }
  175. catch
  176. {
  177. }
  178. _socket = null;
  179. _connected = false;
  180. }
  181. Monitor.Exit(_closeLocker);
  182. }
  183. }
  184. /// <summary>
  185. /// 当连接的结果返回
  186. /// </summary>
  187. /// <param name="ar">异步对象</param>
  188. private void ConnectCallBack(IAsyncResult ar)
  189. {
  190. if (ar.AsyncState is NetStateObject state)
  191. {
  192. if (state.Socket != null)
  193. {
  194. try
  195. {
  196. state.Socket.EndConnect(ar);
  197. state.AutoResetEvent.Set();
  198. }
  199. catch (Exception ex)
  200. {
  201. }
  202. }
  203. }
  204. }
  205. /// <summary>
  206. /// 写日志
  207. /// </summary>
  208. /// <param name="bytes"></param>
  209. /// <param name="logType"></param>
  210. private void WriteInfoLog(byte[] bytes,int logType)
  211. {
  212. if (_logEnabled)
  213. {
  214. string str = string.Join(" ", Array.ConvertAll(bytes, x => x.ToString("X2")));
  215. string type = logType == 0 ? "receive" : "send";
  216. LOG.WriteBackgroundLog(_eventId, _name, $"{type} {str}");
  217. }
  218. }
  219. /// <summary>
  220. /// 发送数据
  221. /// </summary>
  222. /// <param name="data"></param>
  223. /// <returns></returns>
  224. public NetResult Send(byte[] data)
  225. {
  226. if(!Connected)
  227. {
  228. return NetResult.CreateFailedResult(NetErrorCode.NetOffline);
  229. }
  230. //清除缓存数据
  231. ClearPreData();
  232. //进入发送
  233. if (Monitor.TryEnter(_sendLocker,_sendTimeout))
  234. {
  235. if(_socket==null)
  236. {
  237. return NetResult.CreateFailedResult(NetErrorCode.NullSocketObject);
  238. }
  239. try
  240. {
  241. _socket.Send(data);
  242. WriteInfoLog(data, 1);
  243. Monitor.Exit(_sendLocker);
  244. return NetResult.CreateSuccessResult();
  245. }
  246. catch (Exception ex)
  247. {
  248. Monitor.Exit(_sendLocker);
  249. ConnectFailedBusiness();
  250. return NetResult.CreateFailedResult((int)NetErrorCode.InnerException, ex.Message);
  251. }
  252. }
  253. else
  254. {
  255. return NetResult.CreateFailedResult(NetErrorCode.GetLockTimeout);
  256. }
  257. }
  258. /// <summary>
  259. /// 接收数据
  260. /// </summary>
  261. /// <param name="length"></param>
  262. /// <returns></returns>
  263. public NetResult<byte[]> Receive(int length)
  264. {
  265. if (!Connected)
  266. {
  267. return NetResult.CreateFailedResult<byte[]>(NetErrorCode.NetOffline);
  268. }
  269. if (Monitor.TryEnter(_receiveLocker,_receiveTimeout))
  270. {
  271. if(_socket==null)
  272. {
  273. return NetResult.CreateFailedResult<byte[]>(NetErrorCode.NullSocketObject);
  274. }
  275. try
  276. {
  277. byte[] buffer = null;
  278. if (length == -1)
  279. {
  280. buffer = new byte[_socket.Available];
  281. }
  282. else
  283. {
  284. buffer = new byte[length];
  285. }
  286. _socket.Receive(buffer, length, SocketFlags.None);
  287. WriteInfoLog(buffer, 0);
  288. Monitor.Exit(_receiveLocker);
  289. return NetResult.CreateSuccessResult<byte[]>(buffer);
  290. }
  291. catch(SocketException ex)
  292. {
  293. Monitor.Exit(_receiveLocker);
  294. ConnectFailedBusiness();
  295. return NetResult.CreateFailedResult<byte[]>((int)NetErrorCode.InnerException, ex.Message);
  296. }
  297. catch (Exception ex)
  298. {
  299. Monitor.Exit(_receiveLocker);
  300. ConnectFailedBusiness();
  301. return NetResult.CreateFailedResult<byte[]>((int)NetErrorCode.InnerException, ex.Message);
  302. }
  303. }
  304. else
  305. {
  306. return NetResult.CreateFailedResult<byte[]>(NetErrorCode.GetLockTimeout);
  307. }
  308. }
  309. /// <summary>
  310. /// 清除先前的数据
  311. /// </summary>
  312. public void ClearPreData()
  313. {
  314. if (!Connected)
  315. {
  316. return;
  317. }
  318. if (Monitor.TryEnter(_receiveLocker, _receiveTimeout))
  319. {
  320. if (_socket == null)
  321. {
  322. return;
  323. }
  324. try
  325. {
  326. while (_socket.Available != 0)
  327. {
  328. byte[] buffer = new byte[_socket.Available];
  329. _socket.Receive(buffer, buffer.Length, SocketFlags.None);
  330. }
  331. Monitor.Exit(_receiveLocker);
  332. }
  333. catch (SocketException ex)
  334. {
  335. Monitor.Exit(_receiveLocker);
  336. ConnectFailedBusiness();
  337. }
  338. catch (Exception ex)
  339. {
  340. Monitor.Exit(_receiveLocker);
  341. ConnectFailedBusiness();
  342. }
  343. }
  344. }
  345. }
  346. }