TChannel.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. stream.Seek(Packet.ActorIdLength, SeekOrigin.Begin); // 外网不需要actorId
  120. ushort messageSize = (ushort) (stream.Length - stream.Position);
  121. this.sendCache.WriteTo(0, messageSize);
  122. this.sendBuffer.Write(this.sendCache, 0, PacketParser.OuterPacketSizeLength);
  123. this.sendBuffer.Write(stream.GetBuffer(), (int)stream.Position, (int)(stream.Length - stream.Position));
  124. break;
  125. }
  126. }
  127. if (!this.isSending)
  128. {
  129. //this.StartSend();
  130. this.Service.NeedStartSend.Add(this.Id);
  131. }
  132. }
  133. private void ConnectAsync()
  134. {
  135. this.outArgs.RemoteEndPoint = this.RemoteAddress;
  136. if (this.socket.ConnectAsync(this.outArgs))
  137. {
  138. return;
  139. }
  140. OnConnectComplete(this.outArgs);
  141. }
  142. private void OnConnectComplete(object o)
  143. {
  144. if (this.socket == null)
  145. {
  146. return;
  147. }
  148. SocketAsyncEventArgs e = (SocketAsyncEventArgs) o;
  149. if (e.SocketError != SocketError.Success)
  150. {
  151. this.OnError((int)e.SocketError);
  152. return;
  153. }
  154. e.RemoteEndPoint = null;
  155. this.isConnected = true;
  156. this.StartRecv();
  157. this.StartSend();
  158. }
  159. private void OnDisconnectComplete(object o)
  160. {
  161. SocketAsyncEventArgs e = (SocketAsyncEventArgs)o;
  162. this.OnError((int)e.SocketError);
  163. }
  164. private void StartRecv()
  165. {
  166. while (true)
  167. {
  168. try
  169. {
  170. if (this.socket == null)
  171. {
  172. return;
  173. }
  174. int size = this.recvBuffer.ChunkSize - this.recvBuffer.LastIndex;
  175. this.innArgs.SetBuffer(this.recvBuffer.Last, this.recvBuffer.LastIndex, size);
  176. }
  177. catch (Exception e)
  178. {
  179. Log.Error($"tchannel error: {this.Id}\n{e}");
  180. this.OnError(ErrorCore.ERR_TChannelRecvError);
  181. return;
  182. }
  183. if (this.socket.ReceiveAsync(this.innArgs))
  184. {
  185. return;
  186. }
  187. this.HandleRecv(this.innArgs);
  188. }
  189. }
  190. private void OnRecvComplete(object o)
  191. {
  192. this.HandleRecv(o);
  193. if (this.socket == null)
  194. {
  195. return;
  196. }
  197. this.StartRecv();
  198. }
  199. private void HandleRecv(object o)
  200. {
  201. if (this.socket == null)
  202. {
  203. return;
  204. }
  205. SocketAsyncEventArgs e = (SocketAsyncEventArgs) o;
  206. if (e.SocketError != SocketError.Success)
  207. {
  208. this.OnError((int)e.SocketError);
  209. return;
  210. }
  211. if (e.BytesTransferred == 0)
  212. {
  213. this.OnError(ErrorCore.ERR_PeerDisconnect);
  214. return;
  215. }
  216. this.recvBuffer.LastIndex += e.BytesTransferred;
  217. if (this.recvBuffer.LastIndex == this.recvBuffer.ChunkSize)
  218. {
  219. this.recvBuffer.AddLast();
  220. this.recvBuffer.LastIndex = 0;
  221. }
  222. // 收到消息回调
  223. while (true)
  224. {
  225. // 这里循环解析消息执行,有可能,执行消息的过程中断开了session
  226. if (this.socket == null)
  227. {
  228. return;
  229. }
  230. try
  231. {
  232. bool ret = this.parser.Parse();
  233. if (!ret)
  234. {
  235. break;
  236. }
  237. this.OnRead(this.parser.MemoryStream);
  238. }
  239. catch (Exception ee)
  240. {
  241. Log.Error($"ip: {this.RemoteAddress} {ee}");
  242. this.OnError(ErrorCore.ERR_SocketError);
  243. return;
  244. }
  245. }
  246. }
  247. public void Update()
  248. {
  249. this.StartSend();
  250. }
  251. private void StartSend()
  252. {
  253. if(!this.isConnected)
  254. {
  255. return;
  256. }
  257. if (this.isSending)
  258. {
  259. return;
  260. }
  261. while (true)
  262. {
  263. try
  264. {
  265. if (this.socket == null)
  266. {
  267. this.isSending = false;
  268. return;
  269. }
  270. // 没有数据需要发送
  271. if (this.sendBuffer.Length == 0)
  272. {
  273. this.isSending = false;
  274. return;
  275. }
  276. this.isSending = true;
  277. int sendSize = this.sendBuffer.ChunkSize - this.sendBuffer.FirstIndex;
  278. if (sendSize > this.sendBuffer.Length)
  279. {
  280. sendSize = (int)this.sendBuffer.Length;
  281. }
  282. this.outArgs.SetBuffer(this.sendBuffer.First, this.sendBuffer.FirstIndex, sendSize);
  283. if (this.socket.SendAsync(this.outArgs))
  284. {
  285. return;
  286. }
  287. HandleSend(this.outArgs);
  288. }
  289. catch (Exception e)
  290. {
  291. throw new Exception($"socket set buffer error: {this.sendBuffer.First.Length}, {this.sendBuffer.FirstIndex}", e);
  292. }
  293. }
  294. }
  295. private void OnSendComplete(object o)
  296. {
  297. HandleSend(o);
  298. this.isSending = false;
  299. this.StartSend();
  300. }
  301. private void HandleSend(object o)
  302. {
  303. if (this.socket == null)
  304. {
  305. return;
  306. }
  307. SocketAsyncEventArgs e = (SocketAsyncEventArgs) o;
  308. if (e.SocketError != SocketError.Success)
  309. {
  310. this.OnError((int)e.SocketError);
  311. return;
  312. }
  313. if (e.BytesTransferred == 0)
  314. {
  315. this.OnError(ErrorCore.ERR_PeerDisconnect);
  316. return;
  317. }
  318. this.sendBuffer.FirstIndex += e.BytesTransferred;
  319. if (this.sendBuffer.FirstIndex == this.sendBuffer.ChunkSize)
  320. {
  321. this.sendBuffer.FirstIndex = 0;
  322. this.sendBuffer.RemoveFirst();
  323. }
  324. }
  325. private void OnRead(MemoryStream memoryStream)
  326. {
  327. try
  328. {
  329. long channelId = this.Id;
  330. this.Service.OnRead(channelId, memoryStream);
  331. }
  332. catch (Exception e)
  333. {
  334. Log.Error($"{this.RemoteAddress} {memoryStream.Length} {e}");
  335. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  336. this.OnError(ErrorCore.ERR_PacketParserError);
  337. }
  338. }
  339. private void OnError(int error)
  340. {
  341. Log.Info($"TChannel OnError: {error} {this.RemoteAddress}");
  342. long channelId = this.Id;
  343. this.Service.Remove(channelId);
  344. this.Service.OnError(channelId, error);
  345. }
  346. #endregion
  347. }
  348. }