WSSession.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Net.WebSockets;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace XGame.Framework.Network
  7. {
  8. public class WSSession : IRemoteSession, IDisposable
  9. {
  10. readonly int TIMEOUT;
  11. private volatile SessionStatus _status = SessionStatus.FREE;
  12. public SessionStatus Status => _status;
  13. public SessionAddress Address { get; private set; }
  14. ClientWebSocket _webSocket;
  15. byte[] _buffer;
  16. CancellationTokenSource _sendSource;
  17. CancellationTokenSource _receiveSource;
  18. ConcurrentQueue<PendingCommand> _pendings;
  19. private ISessionContext _context;
  20. struct PendingCommand
  21. {
  22. public byte[] buffer;
  23. public int offset;
  24. public int length;
  25. }
  26. internal WSSession(int bufferSize, int timeout, ISessionContext context)
  27. {
  28. _buffer = new byte[bufferSize];
  29. TIMEOUT = timeout;
  30. _pendings = new ConcurrentQueue<PendingCommand>();
  31. _sendSource = new CancellationTokenSource();
  32. _receiveSource = new CancellationTokenSource();
  33. _context = context;
  34. }
  35. #region Connect Method
  36. public void Connect(AddressInfo info)
  37. {
  38. if (Status != SessionStatus.FREE)
  39. {
  40. Log.Warn($"[WSSession] SessionStatus:{Status} 已连接或者正在连接,又尝试连接");
  41. return;
  42. }
  43. OnStartConnect();
  44. if (Address == null ||
  45. Address.Domain != info.Address ||
  46. Address.PORT == info.Port ||
  47. Address.ProtocolType == info.ProtocolType)
  48. {
  49. Address = new SessionAddress(info);
  50. }
  51. var uri = GetUri(Address);
  52. if (uri == null)
  53. {
  54. OnConnectFail(new Exception($"[WSSession] ProtocolType {Address.ProtocolType} is not find"));
  55. return;
  56. }
  57. StartConnect(uri).ConfigureAwait(false);
  58. }
  59. Uri GetUri(SessionAddress info)
  60. {
  61. string url;
  62. switch (info.ProtocolType)
  63. {
  64. case ProtocolType.WS:
  65. if (string.IsNullOrEmpty(info.URI))
  66. url = $"ws://{info.Domain}:{info.PORT}";
  67. else
  68. url = info.URI;
  69. break;
  70. case ProtocolType.WSS:
  71. if (string.IsNullOrEmpty(info.URI))
  72. url = $"wss://{info.Domain}:{info.PORT}";
  73. else
  74. url = info.URI;
  75. break;
  76. default:
  77. return null;
  78. }
  79. return new Uri(url);
  80. }
  81. async Task StartConnect(Uri uri)
  82. {
  83. await Task.Run(() =>
  84. {
  85. _status = SessionStatus.CONNECTING;
  86. var webSocket = new ClientWebSocket();
  87. webSocket.Options.KeepAliveInterval = new TimeSpan(0, 0, 30);
  88. webSocket.Options.Proxy = null;
  89. webSocket.Options.UseDefaultCredentials = true;
  90. try
  91. {
  92. IAsyncResult asyncResult = webSocket.ConnectAsync(uri, CancellationToken.None);
  93. var success = asyncResult.AsyncWaitHandle.WaitOne(TIMEOUT, true);
  94. if (success && webSocket.State == WebSocketState.Open)
  95. {
  96. while (_pendings.TryDequeue(out var _)) ; // clear pendings
  97. _webSocket = webSocket;
  98. if (_sendSource != null)
  99. try { _sendSource.Dispose(); } catch { }
  100. if (_receiveSource != null)
  101. try { _receiveSource.Dispose(); } catch { }
  102. _sendSource = new CancellationTokenSource();
  103. _receiveSource = new CancellationTokenSource();
  104. _ = Task.Run(() => LoopSendAsync().ConfigureAwait(false));
  105. _ = Task.Run(() => LoopReceiveAsync().ConfigureAwait(false));
  106. OnConnected();
  107. }
  108. else
  109. {
  110. Log.Debug($"[Net] WSSession Connect failed. Result:{success} State:{webSocket.State}");
  111. webSocket.Dispose();
  112. OnConnectTimeout();
  113. }
  114. }
  115. catch (Exception e)
  116. {
  117. webSocket.Dispose();
  118. OnConnectFail(e);
  119. }
  120. });
  121. }
  122. #endregion
  123. #region Disconnect Method
  124. public void Disconnect()
  125. {
  126. if (Status != SessionStatus.FREE)
  127. {
  128. Exception exception = null;
  129. _sendSource.Cancel();
  130. try
  131. {
  132. if (_webSocket != null && _webSocket.State == WebSocketState.Open)
  133. {
  134. IAsyncResult resultAsync = _webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
  135. resultAsync.AsyncWaitHandle.WaitOne(TIMEOUT, true);
  136. }
  137. else
  138. {
  139. Log.Debug($"[WSSession] CloseOutputAsync else!!!: Status: {Status}, Time: {DateTime.Now.ToLongTimeString()}:{DateTime.Now.Millisecond}, State: {_webSocket?.State}, IsNull: {_webSocket == null}");
  140. }
  141. }
  142. catch (Exception e)
  143. {
  144. exception = e;
  145. }
  146. finally
  147. {
  148. _receiveSource.Cancel();
  149. try { _webSocket?.Dispose(); } catch { }
  150. _webSocket = null;
  151. _status = SessionStatus.FREE;
  152. if (exception != null)
  153. OnDisconnectError(exception);
  154. OnDisconnect();
  155. }
  156. }
  157. }
  158. #endregion
  159. public bool IsConnected(bool bPrecice)
  160. {
  161. return _webSocket != null && Status == SessionStatus.CONNECTED;
  162. }
  163. public bool Send(byte[] bytes, int offset, int length)
  164. {
  165. PendingCommand cmd = new PendingCommand()
  166. {
  167. buffer = bytes,
  168. offset = offset,
  169. length = length
  170. };
  171. _pendings.Enqueue(cmd);
  172. return true;
  173. }
  174. async Task LoopSendAsync()
  175. {
  176. var cancelToken = _sendSource.Token;
  177. Log.Debug($"[WSSession] LoopSendAsync Start: Status: {Status}, Time: {DateTime.Now.ToLongTimeString()}:{DateTime.Now.Millisecond}, State: {_webSocket?.State}, IsNull: {_webSocket == null}, SourceIsCanceled: {_sendSource.IsCancellationRequested}, TokenIsCanceled: {cancelToken.IsCancellationRequested}");
  178. try
  179. {
  180. while (_webSocket.State != WebSocketState.Closed && !cancelToken.IsCancellationRequested)
  181. {
  182. cancelToken.ThrowIfCancellationRequested();
  183. while (_pendings.TryDequeue(out var cmd))
  184. {
  185. var buffer = new ArraySegment<byte>(cmd.buffer, cmd.offset, cmd.length);
  186. cancelToken.ThrowIfCancellationRequested();
  187. await _webSocket.SendAsync(buffer, WebSocketMessageType.Binary, true, cancelToken).ConfigureAwait(false);
  188. cancelToken.ThrowIfCancellationRequested();
  189. SessionBufferPool.Recycle(cmd.buffer);
  190. }
  191. Thread.Sleep(1);
  192. }
  193. }
  194. catch (OperationCanceledException oce)
  195. {
  196. Log.WarnException("[WSSession] Normal upon task/token cancellation, disregard", oce);
  197. }
  198. catch (Exception e)
  199. {
  200. OnSendError(e);
  201. }
  202. finally
  203. {
  204. Log.Debug($"[WSSession] LoopSendAsync Exit: Status: {Status}, Time: {DateTime.Now.ToLongTimeString()}:{DateTime.Now.Millisecond}, State: {_webSocket?.State}, IsNull: {_webSocket == null}, SourceIsCanceled: {_sendSource.IsCancellationRequested}, TokenIsCanceled: {cancelToken.IsCancellationRequested}");
  205. }
  206. }
  207. async Task LoopReceiveAsync()
  208. {
  209. var cancelToken = _receiveSource.Token;
  210. Log.Debug($"[WSSession] LoopReceiveAsync Start: Status: {Status}, Time: {DateTime.Now.ToLongTimeString()}:{DateTime.Now.Millisecond}, State: {_webSocket?.State}, IsNull: {_webSocket == null}, SourceIsCanceled: {_receiveSource.IsCancellationRequested}, TokenIsCanceled: {cancelToken.IsCancellationRequested}");
  211. Exception exception = null;
  212. try
  213. {
  214. var buffer = new ArraySegment<byte>(_buffer, 0, _buffer.Length);
  215. while (_webSocket.State != WebSocketState.Closed && !cancelToken.IsCancellationRequested)
  216. {
  217. cancelToken.ThrowIfCancellationRequested();
  218. var receiveResult = await _webSocket.ReceiveAsync(buffer, cancelToken).ConfigureAwait(false);
  219. if (!cancelToken.IsCancellationRequested)
  220. {
  221. if (_webSocket.State == WebSocketState.CloseReceived && receiveResult.MessageType == WebSocketMessageType.Close)
  222. {
  223. _sendSource.Cancel();
  224. await _webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Acknowledge Close frame", CancellationToken.None).ConfigureAwait(false);
  225. OnRemoteClose();
  226. }
  227. if (_webSocket.State == WebSocketState.Open && receiveResult.MessageType != WebSocketMessageType.Close)
  228. {
  229. int length = receiveResult.Count;
  230. if (length > 0)
  231. OnRead(buffer.Array, buffer.Offset, length);
  232. }
  233. }
  234. Thread.Sleep(1);
  235. if (Status == SessionStatus.FREE)
  236. throw new OperationCanceledException("No cancel after disconnected...");
  237. }
  238. }
  239. catch (OperationCanceledException oce)
  240. {
  241. Log.WarnException("[WSSession] Normal upon task/token cancellation, disregard", oce);
  242. }
  243. catch (Exception e)
  244. {
  245. exception = e;
  246. }
  247. finally
  248. {
  249. _sendSource.Cancel();
  250. if (exception != null)
  251. OnReceiveError(exception);
  252. }
  253. Log.Debug($"[WSSession] LoopReceiveAsync Exit: Status: {Status}, Time: {DateTime.Now.ToLongTimeString()}:{DateTime.Now.Millisecond}, State: {_webSocket?.State}, IsNull: {_webSocket == null}, SourceIsCanceled: {_receiveSource.IsCancellationRequested}, TokenIsCanceled: {cancelToken.IsCancellationRequested}");
  254. }
  255. void OnRead(byte[] bytes, int offset, int length)
  256. {
  257. var buffer = SessionBufferPool.Acquire();
  258. Array.Copy(bytes, offset, buffer, 0, length);
  259. _context.Synchronizer.Enqueue(buffer, 0, length);
  260. }
  261. void IDisposable.Dispose()
  262. {
  263. Disconnect();
  264. _context = null;
  265. }
  266. #region Event
  267. private void OnConnectFail(Exception e)
  268. {
  269. _status = SessionStatus.CONNECT_FAIL;
  270. _context.Synchronizer.Enqueue(ESessionCode.ConnectFail, e);
  271. }
  272. private void OnConnectTimeout()
  273. {
  274. _status = SessionStatus.CONNECT_TIMEOUT;
  275. _context.Synchronizer.Enqueue(ESessionCode.ConnectTimeout, null);
  276. }
  277. private void OnConnected()
  278. {
  279. _status = SessionStatus.CONNECTED;
  280. _context.Synchronizer.Enqueue(ESessionCode.Connected, null);
  281. }
  282. private void OnStartConnect()
  283. {
  284. _context.Synchronizer.Enqueue(ESessionCode.StartConnect, null);
  285. }
  286. private void OnDisconnect()
  287. {
  288. _context.Synchronizer.Enqueue(ESessionCode.Disconnect, null);
  289. }
  290. private void OnDisconnectError(Exception e)
  291. {
  292. _context.Synchronizer.Enqueue(ESessionCode.DisconnectError, e);
  293. }
  294. private void OnSendError(Exception e)
  295. {
  296. _status = SessionStatus.SEND_ERROR;
  297. _context.Synchronizer.Enqueue(ESessionCode.SendException, e);
  298. }
  299. private void OnReceiveError(Exception e)
  300. {
  301. _status = SessionStatus.RECV_ERROR;
  302. _context.Synchronizer.Enqueue(ESessionCode.RecvError, e);
  303. }
  304. private void OnRemoteClose()
  305. {
  306. _status = SessionStatus.CLOSED;
  307. _context.Synchronizer.Enqueue(ESessionCode.SessionClose, null);
  308. }
  309. #endregion
  310. }
  311. }