TChannel.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. namespace KYFramework.Network
  6. {
  7. /// <summary>
  8. /// 封装Socket,将回调push到主线程处理
  9. /// </summary>
  10. public sealed class TChannel: AChannel
  11. {
  12. private Socket socket;
  13. private SocketAsyncEventArgs innArgs = new SocketAsyncEventArgs();
  14. private SocketAsyncEventArgs outArgs = new SocketAsyncEventArgs();
  15. private readonly CircularBuffer recvBuffer = new CircularBuffer();
  16. private readonly CircularBuffer sendBuffer = new CircularBuffer();
  17. private readonly MemoryStream memoryStream;
  18. private bool isSending;
  19. private bool isRecving;
  20. private bool isConnected;
  21. private readonly PacketParser parser;
  22. private readonly byte[] packetSizeCache;
  23. public TChannel(IPEndPoint ipEndPoint, TService service): base(service, ChannelType.Connect)
  24. {
  25. int packetSize = service.PacketSizeLength;
  26. this.packetSizeCache = new byte[packetSize];
  27. this.memoryStream = service.MemoryStreamManager.GetStream("message", ushort.MaxValue);
  28. this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  29. this.socket.NoDelay = true;
  30. this.parser = new PacketParser(packetSize, this.recvBuffer, this.memoryStream);
  31. this.innArgs.Completed += this.OnComplete;
  32. this.outArgs.Completed += this.OnComplete;
  33. this.RemoteAddress = ipEndPoint;
  34. this.isConnected = false;
  35. this.isSending = false;
  36. }
  37. public TChannel(Socket socket, TService service): base(service, ChannelType.Accept)
  38. {
  39. int packetSize = service.PacketSizeLength;
  40. this.packetSizeCache = new byte[packetSize];
  41. this.memoryStream = service.MemoryStreamManager.GetStream("message", ushort.MaxValue);
  42. this.socket = socket;
  43. this.socket.NoDelay = true;
  44. this.parser = new PacketParser(packetSize, this.recvBuffer, this.memoryStream);
  45. this.innArgs.Completed += this.OnComplete;
  46. this.outArgs.Completed += this.OnComplete;
  47. this.RemoteAddress = (IPEndPoint)socket.RemoteEndPoint;
  48. this.isConnected = true;
  49. this.isSending = false;
  50. }
  51. public override void Dispose()
  52. {
  53. if (this.IsDisposed)
  54. {
  55. return;
  56. }
  57. base.Dispose();
  58. this.socket.Close();
  59. this.innArgs.Dispose();
  60. this.outArgs.Dispose();
  61. this.innArgs = null;
  62. this.outArgs = null;
  63. this.socket = null;
  64. this.memoryStream.Dispose();
  65. }
  66. private TService GetService()
  67. {
  68. return (TService)this.Service;
  69. }
  70. public override MemoryStream Stream
  71. {
  72. get
  73. {
  74. return this.memoryStream;
  75. }
  76. }
  77. public override void Start()
  78. {
  79. if (!this.isConnected)
  80. {
  81. this.ConnectAsync(this.RemoteAddress);
  82. return;
  83. }
  84. if (!this.isRecving)
  85. {
  86. this.isRecving = true;
  87. this.StartRecv();
  88. }
  89. this.GetService().MarkNeedStartSend(this.Id);
  90. }
  91. public override void Send(MemoryStream stream)
  92. {
  93. if (this.IsDisposed)
  94. {
  95. throw new Exception("TChannel已经被Dispose, 不能发送消息");
  96. }
  97. switch (this.GetService().PacketSizeLength)
  98. {
  99. case Packet.PacketSizeLength4:
  100. if (stream.Length > ushort.MaxValue * 16)
  101. {
  102. throw new Exception($"send packet too large: {stream.Length}");
  103. }
  104. this.packetSizeCache.WriteTo(0, (int) stream.Length);
  105. break;
  106. case Packet.PacketSizeLength2:
  107. if (stream.Length > ushort.MaxValue)
  108. {
  109. throw new Exception($"send packet too large: {stream.Length}");
  110. }
  111. this.packetSizeCache.WriteTo(0, (ushort) stream.Length);
  112. break;
  113. default:
  114. throw new Exception("packet size must be 2 or 4!");
  115. }
  116. this.sendBuffer.Write(this.packetSizeCache, 0, this.packetSizeCache.Length);
  117. this.sendBuffer.Write(stream);
  118. this.GetService().MarkNeedStartSend(this.Id);
  119. }
  120. private void OnComplete(object sender, SocketAsyncEventArgs e)
  121. {
  122. switch (e.LastOperation)
  123. {
  124. case SocketAsyncOperation.Connect:
  125. OneThreadSynchronizationContext.Instance.Post(this.OnConnectComplete, e);
  126. break;
  127. case SocketAsyncOperation.Receive:
  128. OneThreadSynchronizationContext.Instance.Post(this.OnRecvComplete, e);
  129. break;
  130. case SocketAsyncOperation.Send:
  131. OneThreadSynchronizationContext.Instance.Post(this.OnSendComplete, e);
  132. break;
  133. case SocketAsyncOperation.Disconnect:
  134. OneThreadSynchronizationContext.Instance.Post(this.OnDisconnectComplete, e);
  135. break;
  136. default:
  137. throw new Exception($"socket error: {e.LastOperation}");
  138. }
  139. }
  140. public void ConnectAsync(IPEndPoint ipEndPoint)
  141. {
  142. this.outArgs.RemoteEndPoint = ipEndPoint;
  143. if (this.socket.ConnectAsync(this.outArgs))
  144. {
  145. return;
  146. }
  147. OnConnectComplete(this.outArgs);
  148. }
  149. private void OnConnectComplete(object o)
  150. {
  151. if (this.socket == null)
  152. {
  153. return;
  154. }
  155. SocketAsyncEventArgs e = (SocketAsyncEventArgs) o;
  156. if (e.SocketError != SocketError.Success)
  157. {
  158. this.OnError((int)e.SocketError);
  159. return;
  160. }
  161. e.RemoteEndPoint = null;
  162. this.isConnected = true;
  163. this.Start();
  164. }
  165. private void OnDisconnectComplete(object o)
  166. {
  167. SocketAsyncEventArgs e = (SocketAsyncEventArgs)o;
  168. this.OnError((int)e.SocketError);
  169. }
  170. private void StartRecv()
  171. {
  172. int size = this.recvBuffer.ChunkSize - this.recvBuffer.LastIndex;
  173. this.RecvAsync(this.recvBuffer.Last, this.recvBuffer.LastIndex, size);
  174. }
  175. public void RecvAsync(byte[] buffer, int offset, int count)
  176. {
  177. try
  178. {
  179. this.innArgs.SetBuffer(buffer, offset, count);
  180. }
  181. catch (Exception e)
  182. {
  183. throw new Exception($"socket set buffer error: {buffer.Length}, {offset}, {count}", e);
  184. }
  185. if (this.socket.ReceiveAsync(this.innArgs))
  186. {
  187. return;
  188. }
  189. OnRecvComplete(this.innArgs);
  190. }
  191. private void OnRecvComplete(object o)
  192. {
  193. if (this.socket == null)
  194. {
  195. return;
  196. }
  197. SocketAsyncEventArgs e = (SocketAsyncEventArgs) o;
  198. if (e.SocketError != SocketError.Success)
  199. {
  200. this.OnError((int)e.SocketError);
  201. return;
  202. }
  203. if (e.BytesTransferred == 0)
  204. {
  205. this.OnError(ErrorCode.ERR_PeerDisconnect);
  206. return;
  207. }
  208. this.recvBuffer.LastIndex += e.BytesTransferred;
  209. if (this.recvBuffer.LastIndex == this.recvBuffer.ChunkSize)
  210. {
  211. this.recvBuffer.AddLast();
  212. this.recvBuffer.LastIndex = 0;
  213. }
  214. // 收到消息回调
  215. while (true)
  216. {
  217. try
  218. {
  219. if (!this.parser.Parse())
  220. {
  221. break;
  222. }
  223. }
  224. catch (Exception ee)
  225. {
  226. Log.Error(ee);
  227. this.OnError(ErrorCode.ERR_SocketError);
  228. return;
  229. }
  230. try
  231. {
  232. this.OnRead(this.parser.GetPacket());
  233. }
  234. catch (Exception ee)
  235. {
  236. Log.Error(ee);
  237. }
  238. }
  239. if (this.socket == null)
  240. {
  241. return;
  242. }
  243. this.StartRecv();
  244. }
  245. public bool IsSending => this.isSending;
  246. public void StartSend()
  247. {
  248. if(!this.isConnected)
  249. {
  250. return;
  251. }
  252. // 没有数据需要发送
  253. if (this.sendBuffer.Length == 0)
  254. {
  255. this.isSending = false;
  256. return;
  257. }
  258. this.isSending = true;
  259. int sendSize = this.sendBuffer.ChunkSize - this.sendBuffer.FirstIndex;
  260. if (sendSize > this.sendBuffer.Length)
  261. {
  262. sendSize = (int)this.sendBuffer.Length;
  263. }
  264. this.SendAsync(this.sendBuffer.First, this.sendBuffer.FirstIndex, sendSize);
  265. }
  266. public void SendAsync(byte[] buffer, int offset, int count)
  267. {
  268. try
  269. {
  270. this.outArgs.SetBuffer(buffer, offset, count);
  271. }
  272. catch (Exception e)
  273. {
  274. throw new Exception($"socket set buffer error: {buffer.Length}, {offset}, {count}", e);
  275. }
  276. if (this.socket.SendAsync(this.outArgs))
  277. {
  278. return;
  279. }
  280. OnSendComplete(this.outArgs);
  281. }
  282. private void OnSendComplete(object o)
  283. {
  284. if (this.socket == null)
  285. {
  286. return;
  287. }
  288. SocketAsyncEventArgs e = (SocketAsyncEventArgs) o;
  289. if (e.SocketError != SocketError.Success)
  290. {
  291. this.OnError((int)e.SocketError);
  292. return;
  293. }
  294. if (e.BytesTransferred == 0)
  295. {
  296. this.OnError(ErrorCode.ERR_PeerDisconnect);
  297. return;
  298. }
  299. this.sendBuffer.FirstIndex += e.BytesTransferred;
  300. if (this.sendBuffer.FirstIndex == this.sendBuffer.ChunkSize)
  301. {
  302. this.sendBuffer.FirstIndex = 0;
  303. this.sendBuffer.RemoveFirst();
  304. }
  305. this.StartSend();
  306. }
  307. }
  308. }