WChannel.cs 7.4 KB

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