TChannel.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. namespace ET
  6. {
  7. /// <summary>
  8. /// 封装Socket,将回调push到主线程处理
  9. /// </summary>
  10. public sealed class TChannel: AChannel
  11. {
  12. private readonly TService Service;
  13. private Socket socket;
  14. private SocketAsyncEventArgs innArgs = new SocketAsyncEventArgs();
  15. private SocketAsyncEventArgs outArgs = new SocketAsyncEventArgs();
  16. private readonly CircularBuffer recvBuffer = new CircularBuffer();
  17. private readonly CircularBuffer sendBuffer = new CircularBuffer();
  18. private bool isSending;
  19. private bool isConnected;
  20. private readonly PacketParser parser;
  21. private readonly byte[] sendCache = new byte[Packet.OpcodeLength + Packet.ActorIdLength];
  22. private void OnComplete(object sender, SocketAsyncEventArgs e)
  23. {
  24. switch (e.LastOperation)
  25. {
  26. case SocketAsyncOperation.Connect:
  27. this.Service.ThreadSynchronizationContext.Post(()=>OnConnectComplete(e));
  28. break;
  29. case SocketAsyncOperation.Receive:
  30. this.Service.ThreadSynchronizationContext.Post(()=>OnRecvComplete(e));
  31. break;
  32. case SocketAsyncOperation.Send:
  33. this.Service.ThreadSynchronizationContext.Post(()=>OnSendComplete(e));
  34. break;
  35. case SocketAsyncOperation.Disconnect:
  36. this.Service.ThreadSynchronizationContext.Post(()=>OnDisconnectComplete(e));
  37. break;
  38. default:
  39. throw new Exception($"socket error: {e.LastOperation}");
  40. }
  41. }
  42. #region 网络线程
  43. public TChannel(long id, IPEndPoint ipEndPoint, TService service)
  44. {
  45. this.ChannelType = ChannelType.Connect;
  46. this.Id = id;
  47. this.Service = service;
  48. this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  49. this.socket.NoDelay = true;
  50. this.parser = new PacketParser(this.recvBuffer, this.Service);
  51. this.innArgs.Completed += this.OnComplete;
  52. this.outArgs.Completed += this.OnComplete;
  53. this.RemoteAddress = ipEndPoint;
  54. this.isConnected = false;
  55. this.isSending = false;
  56. this.Service.ThreadSynchronizationContext.PostNext(this.ConnectAsync);
  57. }
  58. public TChannel(long id, Socket socket, TService service)
  59. {
  60. this.ChannelType = ChannelType.Accept;
  61. this.Id = id;
  62. this.Service = service;
  63. this.socket = socket;
  64. this.socket.NoDelay = true;
  65. this.parser = new PacketParser(this.recvBuffer, this.Service);
  66. this.innArgs.Completed += this.OnComplete;
  67. this.outArgs.Completed += this.OnComplete;
  68. this.RemoteAddress = (IPEndPoint)socket.RemoteEndPoint;
  69. this.isConnected = true;
  70. this.isSending = false;
  71. // 下一帧再开始读写
  72. this.Service.ThreadSynchronizationContext.PostNext(() =>
  73. {
  74. this.StartRecv();
  75. this.StartSend();
  76. });
  77. }
  78. public override void Dispose()
  79. {
  80. if (this.IsDisposed)
  81. {
  82. return;
  83. }
  84. Log.Info($"channel dispose: {this.Id} {this.RemoteAddress}");
  85. long id = this.Id;
  86. this.Id = 0;
  87. this.Service.Remove(id);
  88. this.socket.Close();
  89. this.innArgs.Dispose();
  90. this.outArgs.Dispose();
  91. this.innArgs = null;
  92. this.outArgs = null;
  93. this.socket = null;
  94. }
  95. public void Send(long actorId, MemoryStream stream)
  96. {
  97. if (this.IsDisposed)
  98. {
  99. throw new Exception("TChannel已经被Dispose, 不能发送消息");
  100. }
  101. switch (this.Service.ServiceType)
  102. {
  103. case ServiceType.Inner:
  104. {
  105. int messageSize = (int) (stream.Length - stream.Position);
  106. if (messageSize > ushort.MaxValue * 16)
  107. {
  108. throw new Exception($"send packet too large: {stream.Length} {stream.Position}");
  109. }
  110. this.sendCache.WriteTo(0, messageSize);
  111. this.sendBuffer.Write(this.sendCache, 0, PacketParser.InnerPacketSizeLength);
  112. // actorId
  113. stream.GetBuffer().WriteTo(0, actorId);
  114. this.sendBuffer.Write(stream.GetBuffer(), (int)stream.Position, (int)(stream.Length - stream.Position));
  115. break;
  116. }
  117. case ServiceType.Outer:
  118. {
  119. ushort messageSize = (ushort) (stream.Length - stream.Position);
  120. this.sendCache.WriteTo(0, messageSize);
  121. this.sendBuffer.Write(this.sendCache, 0, PacketParser.OuterPacketSizeLength);
  122. this.sendBuffer.Write(stream.GetBuffer(), (int)stream.Position, (int)(stream.Length - stream.Position));
  123. break;
  124. }
  125. }
  126. if (!this.isSending)
  127. {
  128. //this.StartSend();
  129. this.Service.NeedStartSend.Add(this.Id);
  130. }
  131. }
  132. private void ConnectAsync()
  133. {
  134. this.outArgs.RemoteEndPoint = this.RemoteAddress;
  135. if (this.socket.ConnectAsync(this.outArgs))
  136. {
  137. return;
  138. }
  139. OnConnectComplete(this.outArgs);
  140. }
  141. private void OnConnectComplete(object o)
  142. {
  143. if (this.socket == null)
  144. {
  145. return;
  146. }
  147. SocketAsyncEventArgs e = (SocketAsyncEventArgs) o;
  148. if (e.SocketError != SocketError.Success)
  149. {
  150. this.OnError((int)e.SocketError);
  151. return;
  152. }
  153. e.RemoteEndPoint = null;
  154. this.isConnected = true;
  155. this.StartRecv();
  156. this.StartSend();
  157. }
  158. private void OnDisconnectComplete(object o)
  159. {
  160. SocketAsyncEventArgs e = (SocketAsyncEventArgs)o;
  161. this.OnError((int)e.SocketError);
  162. }
  163. private void StartRecv()
  164. {
  165. while (true)
  166. {
  167. try
  168. {
  169. if (this.socket == null)
  170. {
  171. return;
  172. }
  173. int size = this.recvBuffer.ChunkSize - this.recvBuffer.LastIndex;
  174. this.innArgs.SetBuffer(this.recvBuffer.Last, this.recvBuffer.LastIndex, size);
  175. }
  176. catch (Exception e)
  177. {
  178. Log.Error($"tchannel error: {this.Id}\n{e}");
  179. this.OnError(ErrorCode.ERR_TChannelRecvError);
  180. return;
  181. }
  182. if (this.socket.ReceiveAsync(this.innArgs))
  183. {
  184. return;
  185. }
  186. this.HandleRecv(this.innArgs);
  187. }
  188. }
  189. private void OnRecvComplete(object o)
  190. {
  191. this.HandleRecv(o);
  192. if (this.socket == null)
  193. {
  194. return;
  195. }
  196. this.StartRecv();
  197. }
  198. private void HandleRecv(object o)
  199. {
  200. if (this.socket == null)
  201. {
  202. return;
  203. }
  204. SocketAsyncEventArgs e = (SocketAsyncEventArgs) o;
  205. if (e.SocketError != SocketError.Success)
  206. {
  207. this.OnError((int)e.SocketError);
  208. return;
  209. }
  210. if (e.BytesTransferred == 0)
  211. {
  212. this.OnError(ErrorCode.ERR_PeerDisconnect);
  213. return;
  214. }
  215. this.recvBuffer.LastIndex += e.BytesTransferred;
  216. if (this.recvBuffer.LastIndex == this.recvBuffer.ChunkSize)
  217. {
  218. this.recvBuffer.AddLast();
  219. this.recvBuffer.LastIndex = 0;
  220. }
  221. // 收到消息回调
  222. while (true)
  223. {
  224. // 这里循环解析消息执行,有可能,执行消息的过程中断开了session
  225. if (this.socket == null)
  226. {
  227. return;
  228. }
  229. try
  230. {
  231. bool ret = this.parser.Parse();
  232. if (!ret)
  233. {
  234. break;
  235. }
  236. this.OnRead(this.parser.MemoryStream);
  237. }
  238. catch (Exception ee)
  239. {
  240. Log.Error($"ip: {this.RemoteAddress} {ee}");
  241. this.OnError(ErrorCode.ERR_SocketError);
  242. return;
  243. }
  244. }
  245. }
  246. public void Update()
  247. {
  248. this.StartSend();
  249. }
  250. private void StartSend()
  251. {
  252. if(!this.isConnected)
  253. {
  254. return;
  255. }
  256. while (true)
  257. {
  258. try
  259. {
  260. if (this.socket == null)
  261. {
  262. return;
  263. }
  264. // 没有数据需要发送
  265. if (this.sendBuffer.Length == 0)
  266. {
  267. this.isSending = false;
  268. return;
  269. }
  270. this.isSending = true;
  271. int sendSize = this.sendBuffer.ChunkSize - this.sendBuffer.FirstIndex;
  272. if (sendSize > this.sendBuffer.Length)
  273. {
  274. sendSize = (int)this.sendBuffer.Length;
  275. }
  276. this.outArgs.SetBuffer(this.sendBuffer.First, this.sendBuffer.FirstIndex, sendSize);
  277. if (this.socket.SendAsync(this.outArgs))
  278. {
  279. return;
  280. }
  281. HandleSend(this.outArgs);
  282. }
  283. catch (Exception e)
  284. {
  285. throw new Exception($"socket set buffer error: {this.sendBuffer.First.Length}, {this.sendBuffer.FirstIndex}", e);
  286. }
  287. }
  288. }
  289. private void OnSendComplete(object o)
  290. {
  291. HandleSend(o);
  292. this.StartSend();
  293. }
  294. private void HandleSend(object o)
  295. {
  296. if (this.socket == null)
  297. {
  298. return;
  299. }
  300. SocketAsyncEventArgs e = (SocketAsyncEventArgs) o;
  301. if (e.SocketError != SocketError.Success)
  302. {
  303. this.OnError((int)e.SocketError);
  304. return;
  305. }
  306. if (e.BytesTransferred == 0)
  307. {
  308. this.OnError(ErrorCode.ERR_PeerDisconnect);
  309. return;
  310. }
  311. this.sendBuffer.FirstIndex += e.BytesTransferred;
  312. if (this.sendBuffer.FirstIndex == this.sendBuffer.ChunkSize)
  313. {
  314. this.sendBuffer.FirstIndex = 0;
  315. this.sendBuffer.RemoveFirst();
  316. }
  317. }
  318. private void OnRead(MemoryStream memoryStream)
  319. {
  320. try
  321. {
  322. long channelId = this.Id;
  323. this.Service.OnRead(channelId, memoryStream);
  324. }
  325. catch (Exception e)
  326. {
  327. Log.Error($"{this.RemoteAddress} {memoryStream.Length} {e}");
  328. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  329. this.OnError(ErrorCode.ERR_PacketParserError);
  330. }
  331. }
  332. private void OnError(int error)
  333. {
  334. Log.Info($"TChannel OnError: {error} {this.RemoteAddress}");
  335. long channelId = this.Id;
  336. this.Service.Remove(channelId);
  337. this.Service.OnError(channelId, error);
  338. }
  339. #endregion
  340. }
  341. }