WChannel.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. ValueWebSocketReceiveResult receiveResult;
  133. int receiveCount = 0;
  134. do
  135. {
  136. receiveResult = await this.webSocket.ReceiveAsync(
  137. new Memory<byte>(cache, receiveCount, this.cache.Length - receiveCount),
  138. cancellationTokenSource.Token);
  139. if (this.IsDisposed)
  140. {
  141. return;
  142. }
  143. receiveCount += receiveResult.Count;
  144. }
  145. while (!receiveResult.EndOfMessage);
  146. if (receiveResult.MessageType == WebSocketMessageType.Close)
  147. {
  148. this.OnError(ErrorCore.ERR_WebsocketPeerReset);
  149. return;
  150. }
  151. if (receiveResult.Count > ushort.MaxValue)
  152. {
  153. await this.webSocket.CloseAsync(WebSocketCloseStatus.MessageTooBig, $"message too big: {receiveCount}",
  154. cancellationTokenSource.Token);
  155. this.OnError(ErrorCore.ERR_WebsocketMessageTooBig);
  156. return;
  157. }
  158. this.recvStream.SetLength(receiveCount);
  159. this.recvStream.Seek(2, SeekOrigin.Begin);
  160. Array.Copy(this.cache, 0, this.recvStream.GetBuffer(), 0, receiveCount);
  161. this.OnRead(this.recvStream);
  162. }
  163. }
  164. catch (Exception e)
  165. {
  166. Log.Error(e);
  167. this.OnError(ErrorCore.ERR_WebsocketRecvError);
  168. }
  169. }
  170. private void OnRead(MemoryStream memoryStream)
  171. {
  172. try
  173. {
  174. long channelId = this.Id;
  175. this.Service.OnRead(channelId, memoryStream);
  176. }
  177. catch (Exception e)
  178. {
  179. Log.Error($"{this.RemoteAddress} {memoryStream.Length} {e}");
  180. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  181. this.OnError(ErrorCore.ERR_PacketParserError);
  182. }
  183. }
  184. private void OnError(int error)
  185. {
  186. Log.Debug($"WChannel error: {error} {this.RemoteAddress}");
  187. long channelId = this.Id;
  188. this.Service.Remove(channelId);
  189. this.Service.OnError(channelId, error);
  190. }
  191. }
  192. }