WSSession.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. webSocket.Dispose();
  111. OnConnectTimeout();
  112. }
  113. }
  114. catch (Exception e)
  115. {
  116. webSocket.Dispose();
  117. OnConnectFail(e);
  118. }
  119. });
  120. }
  121. #endregion
  122. #region Disconnect Method
  123. public void Disconnect()
  124. {
  125. if (Status != SessionStatus.FREE)
  126. {
  127. Exception exception = null;
  128. _sendSource.Cancel();
  129. try
  130. {
  131. if (_webSocket != null && _webSocket.State == WebSocketState.Open)
  132. {
  133. IAsyncResult resultAsync = _webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
  134. resultAsync.AsyncWaitHandle.WaitOne(TIMEOUT, true);
  135. }
  136. else
  137. {
  138. Log.Debug($"[WSSession] CloseOutputAsync else!!!: Status: {Status}, Time: {DateTime.Now.ToLongTimeString()}:{DateTime.Now.Millisecond}, State: {_webSocket?.State}, IsNull: {_webSocket == null}");
  139. }
  140. }
  141. catch (Exception e)
  142. {
  143. exception = e;
  144. }
  145. finally
  146. {
  147. _receiveSource.Cancel();
  148. try { _webSocket?.Dispose(); } catch { }
  149. _webSocket = null;
  150. _status = SessionStatus.FREE;
  151. if (exception != null)
  152. OnDisconnectError(exception);
  153. OnDisconnect();
  154. }
  155. }
  156. }
  157. #endregion
  158. public bool IsConnected(bool bPrecice)
  159. {
  160. return _webSocket != null && Status == SessionStatus.CONNECTED;
  161. }
  162. public bool Send(byte[] bytes, int offset, int length)
  163. {
  164. PendingCommand cmd = new PendingCommand()
  165. {
  166. buffer = bytes,
  167. offset = offset,
  168. length = length
  169. };
  170. _pendings.Enqueue(cmd);
  171. return true;
  172. }
  173. async Task LoopSendAsync()
  174. {
  175. var cancelToken = _sendSource.Token;
  176. 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}");
  177. try
  178. {
  179. while (_webSocket.State != WebSocketState.Closed && !cancelToken.IsCancellationRequested)
  180. {
  181. cancelToken.ThrowIfCancellationRequested();
  182. while (_pendings.TryDequeue(out var cmd))
  183. {
  184. var buffer = new ArraySegment<byte>(cmd.buffer, cmd.offset, cmd.length);
  185. cancelToken.ThrowIfCancellationRequested();
  186. await _webSocket.SendAsync(buffer, WebSocketMessageType.Binary, true, cancelToken).ConfigureAwait(false);
  187. cancelToken.ThrowIfCancellationRequested();
  188. SessionBufferPool.Recycle(cmd.buffer);
  189. }
  190. Thread.Sleep(1);
  191. }
  192. }
  193. catch (OperationCanceledException oce)
  194. {
  195. Log.WarnException("[WSSession] Normal upon task/token cancellation, disregard", oce);
  196. }
  197. catch (Exception e)
  198. {
  199. OnSendError(e);
  200. }
  201. finally
  202. {
  203. 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}");
  204. }
  205. }
  206. async Task LoopReceiveAsync()
  207. {
  208. var cancelToken = _receiveSource.Token;
  209. 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}");
  210. Exception exception = null;
  211. try
  212. {
  213. var buffer = new ArraySegment<byte>(_buffer, 0, _buffer.Length);
  214. while (_webSocket.State != WebSocketState.Closed && !cancelToken.IsCancellationRequested)
  215. {
  216. cancelToken.ThrowIfCancellationRequested();
  217. var receiveResult = await _webSocket.ReceiveAsync(buffer, cancelToken).ConfigureAwait(false);
  218. if (!cancelToken.IsCancellationRequested)
  219. {
  220. if (_webSocket.State == WebSocketState.CloseReceived && receiveResult.MessageType == WebSocketMessageType.Close)
  221. {
  222. _sendSource.Cancel();
  223. await _webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Acknowledge Close frame", CancellationToken.None).ConfigureAwait(false);
  224. OnRemoteClose();
  225. }
  226. if (_webSocket.State == WebSocketState.Open && receiveResult.MessageType != WebSocketMessageType.Close)
  227. {
  228. int length = receiveResult.Count;
  229. if (length > 0)
  230. OnRead(buffer.Array, buffer.Offset, length);
  231. }
  232. }
  233. Thread.Sleep(1);
  234. if (Status == SessionStatus.FREE)
  235. throw new OperationCanceledException("No cancel after disconnected...");
  236. }
  237. }
  238. catch (OperationCanceledException oce)
  239. {
  240. Log.WarnException("[WSSession] Normal upon task/token cancellation, disregard", oce);
  241. }
  242. catch (Exception e)
  243. {
  244. exception = e;
  245. }
  246. finally
  247. {
  248. _sendSource.Cancel();
  249. if (exception != null)
  250. OnReceiveError(exception);
  251. }
  252. 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}");
  253. }
  254. void OnRead(byte[] bytes, int offset, int length)
  255. {
  256. var buffer = SessionBufferPool.Acquire();
  257. Array.Copy(bytes, offset, buffer, 0, length);
  258. _context.Synchronizer.Enqueue(buffer, 0, length);
  259. }
  260. void IDisposable.Dispose()
  261. {
  262. Disconnect();
  263. _context = null;
  264. }
  265. #region Event
  266. private void OnConnectFail(Exception e)
  267. {
  268. _status = SessionStatus.CONNECT_FAIL;
  269. _context.Synchronizer.Enqueue(ESessionCode.ConnectFail, e);
  270. }
  271. private void OnConnectTimeout()
  272. {
  273. _status = SessionStatus.CONNECT_TIMEOUT;
  274. _context.Synchronizer.Enqueue(ESessionCode.ConnectTimeout, null);
  275. }
  276. private void OnConnected()
  277. {
  278. _status = SessionStatus.CONNECTED;
  279. _context.Synchronizer.Enqueue(ESessionCode.Connected, null);
  280. }
  281. private void OnStartConnect()
  282. {
  283. _context.Synchronizer.Enqueue(ESessionCode.StartConnect, null);
  284. }
  285. private void OnDisconnect()
  286. {
  287. _context.Synchronizer.Enqueue(ESessionCode.Disconnect, null);
  288. }
  289. private void OnDisconnectError(Exception e)
  290. {
  291. _context.Synchronizer.Enqueue(ESessionCode.DisconnectError, e);
  292. }
  293. private void OnSendError(Exception e)
  294. {
  295. _status = SessionStatus.SEND_ERROR;
  296. _context.Synchronizer.Enqueue(ESessionCode.SendException, e);
  297. }
  298. private void OnReceiveError(Exception e)
  299. {
  300. _status = SessionStatus.RECV_ERROR;
  301. _context.Synchronizer.Enqueue(ESessionCode.RecvError, e);
  302. }
  303. private void OnRemoteClose()
  304. {
  305. _status = SessionStatus.CLOSED;
  306. _context.Synchronizer.Enqueue(ESessionCode.SessionClose, null);
  307. }
  308. #endregion
  309. }
  310. }