TChannel.cs 5.0 KB

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