WChannel.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net.WebSockets;
  5. using System.Threading;
  6. namespace ET
  7. {
  8. public class WChannel: AChannel
  9. {
  10. public HttpListenerWebSocketContext WebSocketContext { get; }
  11. private readonly WService Service;
  12. private readonly WebSocket webSocket;
  13. private readonly Queue<byte[]> queue = new Queue<byte[]>();
  14. private bool isSending;
  15. private bool isConnected;
  16. private readonly MemoryStream recvStream;
  17. private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
  18. public WChannel(long id, HttpListenerWebSocketContext webSocketContext, WService service)
  19. {
  20. this.Id = id;
  21. this.Service = service;
  22. this.ChannelType = ChannelType.Accept;
  23. this.WebSocketContext = webSocketContext;
  24. this.webSocket = webSocketContext.WebSocket;
  25. this.recvStream = new MemoryStream(ushort.MaxValue);
  26. isConnected = true;
  27. this.Service.ThreadSynchronizationContext.PostNext(()=>
  28. {
  29. this.StartRecv().Coroutine();
  30. this.StartSend().Coroutine();
  31. });
  32. }
  33. public WChannel(long id, WebSocket webSocket, string connectUrl, WService service)
  34. {
  35. this.Id = id;
  36. this.Service = service;
  37. this.ChannelType = ChannelType.Connect;
  38. this.webSocket = webSocket;
  39. this.recvStream = new MemoryStream(ushort.MaxValue);
  40. isConnected = false;
  41. this.Service.ThreadSynchronizationContext.PostNext(()=>this.ConnectAsync(connectUrl).Coroutine());
  42. }
  43. public override void Dispose()
  44. {
  45. if (this.IsDisposed)
  46. {
  47. return;
  48. }
  49. this.cancellationTokenSource.Cancel();
  50. this.cancellationTokenSource.Dispose();
  51. this.cancellationTokenSource = null;
  52. this.webSocket.Dispose();
  53. }
  54. public async ETTask ConnectAsync(string url)
  55. {
  56. try
  57. {
  58. await ((ClientWebSocket) this.webSocket).ConnectAsync(new Uri(url), cancellationTokenSource.Token);
  59. isConnected = true;
  60. this.StartRecv().Coroutine();
  61. this.StartSend().Coroutine();
  62. }
  63. catch (Exception e)
  64. {
  65. Log.Error(e);
  66. this.OnError(ErrorCore.ERR_WebsocketConnectError);
  67. }
  68. }
  69. public void Send(MemoryStream stream)
  70. {
  71. byte[] bytes = new byte[stream.Length - stream.Position];
  72. Array.Copy(stream.GetBuffer(), stream.Position, bytes, 0, bytes.Length);
  73. this.queue.Enqueue(bytes);
  74. if (this.isConnected)
  75. {
  76. this.StartSend().Coroutine();
  77. }
  78. }
  79. public async ETTask StartSend()
  80. {
  81. if (this.IsDisposed)
  82. {
  83. return;
  84. }
  85. try
  86. {
  87. if (this.isSending)
  88. {
  89. return;
  90. }
  91. this.isSending = true;
  92. while (true)
  93. {
  94. if (this.queue.Count == 0)
  95. {
  96. this.isSending = false;
  97. return;
  98. }
  99. byte[] bytes = this.queue.Dequeue();
  100. try
  101. {
  102. await this.webSocket.SendAsync(new ArraySegment<byte>(bytes, 0, bytes.Length), WebSocketMessageType.Binary, true, cancellationTokenSource.Token);
  103. if (this.IsDisposed)
  104. {
  105. return;
  106. }
  107. }
  108. catch (Exception e)
  109. {
  110. Log.Error(e);
  111. this.OnError(ErrorCore.ERR_WebsocketSendError);
  112. return;
  113. }
  114. }
  115. }
  116. catch (Exception e)
  117. {
  118. Log.Error(e);
  119. }
  120. }
  121. private byte[] cache = new byte[ushort.MaxValue];
  122. public async ETTask StartRecv()
  123. {
  124. if (this.IsDisposed)
  125. {
  126. return;
  127. }
  128. try
  129. {
  130. while (true)
  131. {
  132. #if NOT_UNITY
  133. ValueWebSocketReceiveResult receiveResult;
  134. #else
  135. WebSocketReceiveResult receiveResult;
  136. #endif
  137. int receiveCount = 0;
  138. do
  139. {
  140. #if NOT_UNITY
  141. receiveResult = await this.webSocket.ReceiveAsync(
  142. new Memory<byte>(cache, receiveCount, this.cache.Length - receiveCount),
  143. cancellationTokenSource.Token);
  144. #else
  145. receiveResult = await this.webSocket.ReceiveAsync(
  146. new ArraySegment<byte>(this.cache, receiveCount, this.cache.Length - receiveCount),
  147. cancellationTokenSource.Token);
  148. #endif
  149. if (this.IsDisposed)
  150. {
  151. return;
  152. }
  153. receiveCount += receiveResult.Count;
  154. }
  155. while (!receiveResult.EndOfMessage);
  156. if (receiveResult.MessageType == WebSocketMessageType.Close)
  157. {
  158. this.OnError(ErrorCore.ERR_WebsocketPeerReset);
  159. return;
  160. }
  161. if (receiveResult.Count > ushort.MaxValue)
  162. {
  163. await this.webSocket.CloseAsync(WebSocketCloseStatus.MessageTooBig, $"message too big: {receiveCount}",
  164. cancellationTokenSource.Token);
  165. this.OnError(ErrorCore.ERR_WebsocketMessageTooBig);
  166. return;
  167. }
  168. this.recvStream.SetLength(receiveCount);
  169. this.recvStream.Seek(2, SeekOrigin.Begin);
  170. Array.Copy(this.cache, 0, this.recvStream.GetBuffer(), 0, receiveCount);
  171. this.OnRead(this.recvStream);
  172. }
  173. }
  174. catch (Exception e)
  175. {
  176. Log.Error(e);
  177. this.OnError(ErrorCore.ERR_WebsocketRecvError);
  178. }
  179. }
  180. private void OnRead(MemoryStream memoryStream)
  181. {
  182. try
  183. {
  184. long channelId = this.Id;
  185. this.Service.OnRead(channelId, memoryStream);
  186. }
  187. catch (Exception e)
  188. {
  189. Log.Error($"{this.RemoteAddress} {memoryStream.Length} {e}");
  190. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  191. this.OnError(ErrorCore.ERR_PacketParserError);
  192. }
  193. }
  194. private void OnError(int error)
  195. {
  196. Log.Debug($"WChannel error: {error} {this.RemoteAddress}");
  197. long channelId = this.Id;
  198. this.Service.Remove(channelId);
  199. this.Service.OnError(channelId, error);
  200. }
  201. }
  202. }