TChannel.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading.Tasks;
  7. namespace Model
  8. {
  9. public class TChannel : AChannel
  10. {
  11. private readonly TcpClient tcpClient;
  12. private readonly TBuffer recvBuffer = new TBuffer();
  13. private readonly TBuffer sendBuffer = new TBuffer();
  14. private bool isSending;
  15. private readonly PacketParser parser;
  16. private bool isConnected;
  17. private TaskCompletionSource<byte[]> recvTcs;
  18. /// <summary>
  19. /// connect
  20. /// </summary>
  21. public TChannel(TcpClient tcpClient, string host, int port, TService service) : base(service, ChannelType.Connect)
  22. {
  23. this.tcpClient = tcpClient;
  24. this.parser = new PacketParser(this.recvBuffer);
  25. this.RemoteAddress = host + ":" + port;
  26. this.ConnectAsync(host, port);
  27. }
  28. /// <summary>
  29. /// accept
  30. /// </summary>
  31. public TChannel(TcpClient tcpClient, TService service) : base(service, ChannelType.Accept)
  32. {
  33. this.tcpClient = tcpClient;
  34. this.parser = new PacketParser(this.recvBuffer);
  35. IPEndPoint ipEndPoint = (IPEndPoint)this.tcpClient.Client.RemoteEndPoint;
  36. this.RemoteAddress = ipEndPoint.Address + ":" + ipEndPoint.Port;
  37. this.OnAccepted();
  38. }
  39. private async void ConnectAsync(string host, int port)
  40. {
  41. try
  42. {
  43. await this.tcpClient.ConnectAsync(host, port);
  44. this.isConnected = true;
  45. this.StartSend();
  46. this.StartRecv();
  47. }
  48. catch (SocketException e)
  49. {
  50. Log.Error($"connect error: {e.SocketErrorCode}");
  51. }
  52. catch (Exception e)
  53. {
  54. Log.Error(e.ToString());
  55. }
  56. }
  57. public override void Dispose()
  58. {
  59. if (this.Id == 0)
  60. {
  61. return;
  62. }
  63. long id = this.Id;
  64. base.Dispose();
  65. this.tcpClient.Close();
  66. this.service.Remove(id);
  67. }
  68. private void OnAccepted()
  69. {
  70. this.isConnected = true;
  71. this.StartSend();
  72. this.StartRecv();
  73. }
  74. public override void Send(byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
  75. {
  76. if (this.Id == 0)
  77. {
  78. throw new Exception("TChannel已经被Dispose, 不能发送消息");
  79. }
  80. byte[] size = BitConverter.GetBytes((ushort)buffer.Length);
  81. this.sendBuffer.SendTo(size);
  82. this.sendBuffer.SendTo(buffer);
  83. if (this.isConnected)
  84. {
  85. this.StartSend();
  86. }
  87. }
  88. public override void Send(List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
  89. {
  90. if (this.Id == 0)
  91. {
  92. throw new Exception("TChannel已经被Dispose, 不能发送消息");
  93. }
  94. ushort size = (ushort)buffers.Select(b => b.Length).Sum();
  95. size = NetworkHelper.HostToNetworkOrder(size);
  96. byte[] sizeBuffer = BitConverter.GetBytes(size);
  97. this.sendBuffer.SendTo(sizeBuffer);
  98. foreach (byte[] buffer in buffers)
  99. {
  100. this.sendBuffer.SendTo(buffer);
  101. }
  102. if (this.isConnected)
  103. {
  104. this.StartSend();
  105. }
  106. }
  107. private async void StartSend()
  108. {
  109. try
  110. {
  111. // 如果正在发送中,不需要再次发送
  112. if (this.isSending)
  113. {
  114. return;
  115. }
  116. while (true)
  117. {
  118. if (this.Id == 0)
  119. {
  120. return;
  121. }
  122. // 没有数据需要发送
  123. if (this.sendBuffer.Count == 0)
  124. {
  125. this.isSending = false;
  126. return;
  127. }
  128. this.isSending = true;
  129. int sendSize = TBuffer.ChunkSize - this.sendBuffer.FirstIndex;
  130. if (sendSize > this.sendBuffer.Count)
  131. {
  132. sendSize = this.sendBuffer.Count;
  133. }
  134. await this.tcpClient.GetStream().WriteAsync(this.sendBuffer.First, this.sendBuffer.FirstIndex, sendSize);
  135. this.sendBuffer.FirstIndex += sendSize;
  136. if (this.sendBuffer.FirstIndex == TBuffer.ChunkSize)
  137. {
  138. this.sendBuffer.FirstIndex = 0;
  139. this.sendBuffer.RemoveFirst();
  140. }
  141. }
  142. }
  143. catch (Exception e)
  144. {
  145. Log.Error(e.ToString());
  146. this.OnError(this, SocketError.SocketError);
  147. }
  148. }
  149. private async void StartRecv()
  150. {
  151. try
  152. {
  153. while (true)
  154. {
  155. if (this.Id == 0)
  156. {
  157. return;
  158. }
  159. int size = TBuffer.ChunkSize - this.recvBuffer.LastIndex;
  160. int n = await this.tcpClient.GetStream().ReadAsync(this.recvBuffer.Last, this.recvBuffer.LastIndex, size);
  161. if (n == 0)
  162. {
  163. this.OnError(this, SocketError.NetworkReset);
  164. return;
  165. }
  166. this.recvBuffer.LastIndex += n;
  167. if (this.recvBuffer.LastIndex == TBuffer.ChunkSize)
  168. {
  169. this.recvBuffer.AddLast();
  170. this.recvBuffer.LastIndex = 0;
  171. }
  172. if (this.recvTcs != null)
  173. {
  174. byte[] packet = this.parser.GetPacket();
  175. if (packet != null)
  176. {
  177. var tcs = this.recvTcs;
  178. this.recvTcs = null;
  179. tcs.SetResult(packet);
  180. }
  181. }
  182. }
  183. }
  184. catch (ObjectDisposedException)
  185. {
  186. }
  187. catch (Exception e)
  188. {
  189. Log.Error(e.ToString());
  190. this.OnError(this, SocketError.SocketError);
  191. }
  192. }
  193. public override Task<byte[]> Recv()
  194. {
  195. if (this.Id == 0)
  196. {
  197. throw new Exception("TChannel已经被Dispose, 不能接收消息");
  198. }
  199. byte[] packet = this.parser.GetPacket();
  200. if (packet != null)
  201. {
  202. return Task.FromResult(packet);
  203. }
  204. recvTcs = new TaskCompletionSource<byte[]>();
  205. return recvTcs.Task;
  206. }
  207. }
  208. }