Session.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace ETModel
  8. {
  9. [ObjectSystem]
  10. public class SessionAwakeSystem : AwakeSystem<Session, NetworkComponent, AChannel>
  11. {
  12. public override void Awake(Session self, NetworkComponent a, AChannel b)
  13. {
  14. self.Awake(a, b);
  15. }
  16. }
  17. [ObjectSystem]
  18. public class SessionStartSystem : StartSystem<Session>
  19. {
  20. public override void Start(Session self)
  21. {
  22. self.Start();
  23. }
  24. }
  25. public sealed class Session : Entity
  26. {
  27. private static int RpcId { get; set; }
  28. private AChannel channel;
  29. private readonly Dictionary<int, Action<IResponse>> requestCallback = new Dictionary<int, Action<IResponse>>();
  30. private readonly List<byte[]> byteses = new List<byte[]>() { new byte[1], new byte[0], new byte[0]};
  31. public NetworkComponent Network
  32. {
  33. get
  34. {
  35. return this.GetParent<NetworkComponent>();
  36. }
  37. }
  38. public void Awake(NetworkComponent net, AChannel c)
  39. {
  40. this.channel = c;
  41. this.requestCallback.Clear();
  42. }
  43. public void Start()
  44. {
  45. this.StartRecv();
  46. }
  47. public override void Dispose()
  48. {
  49. if (this.IsDisposed)
  50. {
  51. return;
  52. }
  53. long id = this.Id;
  54. base.Dispose();
  55. foreach (Action<IResponse> action in this.requestCallback.Values.ToArray())
  56. {
  57. action.Invoke(new ResponseMessage { Error = ErrorCode.ERR_SocketDisconnected });
  58. }
  59. this.channel.Dispose();
  60. this.Network.Remove(id);
  61. this.requestCallback.Clear();
  62. }
  63. public IPEndPoint RemoteAddress
  64. {
  65. get
  66. {
  67. return this.channel.RemoteAddress;
  68. }
  69. }
  70. public ChannelType ChannelType
  71. {
  72. get
  73. {
  74. return this.channel.ChannelType;
  75. }
  76. }
  77. private async void StartRecv()
  78. {
  79. while (true)
  80. {
  81. if (this.IsDisposed)
  82. {
  83. return;
  84. }
  85. Packet packet;
  86. try
  87. {
  88. packet = await this.channel.Recv();
  89. if (this.IsDisposed)
  90. {
  91. return;
  92. }
  93. }
  94. catch (Exception e)
  95. {
  96. Log.Error(e.ToString());
  97. continue;
  98. }
  99. try
  100. {
  101. this.Run(packet);
  102. }
  103. catch (Exception e)
  104. {
  105. Log.Error(e.ToString());
  106. }
  107. }
  108. }
  109. private void Run(Packet packet)
  110. {
  111. if (packet.Length < Packet.MinSize)
  112. {
  113. Log.Error($"message error length < {Packet.MinSize}, ip: {this.RemoteAddress}");
  114. this.Network.Remove(this.Id);
  115. return;
  116. }
  117. byte flag = packet.Flag();
  118. ushort opcode = packet.Opcode();
  119. #if !SERVER
  120. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  121. {
  122. this.Network.MessageDispatcher.Dispatch(this, packet);
  123. return;
  124. }
  125. #endif
  126. // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
  127. if ((flag & 0x01) == 0)
  128. {
  129. this.Network.MessageDispatcher.Dispatch(this, packet);
  130. return;
  131. }
  132. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  133. Type responseType = opcodeTypeComponent.GetType(opcode);
  134. object message = this.Network.MessagePacker.DeserializeFrom(responseType, packet.Bytes, Packet.Index, packet.Length - Packet.Index);
  135. IResponse response = message as IResponse;
  136. if (response == null)
  137. {
  138. throw new Exception($"flag is response, but message is not! {opcode}");
  139. }
  140. Action<IResponse> action;
  141. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  142. {
  143. return;
  144. }
  145. this.requestCallback.Remove(response.RpcId);
  146. action(response);
  147. }
  148. public Task<IResponse> Call(IRequest request)
  149. {
  150. int rpcId = ++RpcId;
  151. var tcs = new TaskCompletionSource<IResponse>();
  152. this.requestCallback[rpcId] = (response) =>
  153. {
  154. try
  155. {
  156. if (response.Error > ErrorCode.ERR_Exception)
  157. {
  158. throw new RpcException(response.Error, response.Message);
  159. }
  160. tcs.SetResult(response);
  161. }
  162. catch (Exception e)
  163. {
  164. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  165. }
  166. };
  167. request.RpcId = rpcId;
  168. this.Send(0x00, request);
  169. return tcs.Task;
  170. }
  171. public Task<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  172. {
  173. int rpcId = ++RpcId;
  174. var tcs = new TaskCompletionSource<IResponse>();
  175. this.requestCallback[rpcId] = (response) =>
  176. {
  177. try
  178. {
  179. if (response.Error > ErrorCode.ERR_Exception)
  180. {
  181. throw new RpcException(response.Error, response.Message);
  182. }
  183. tcs.SetResult(response);
  184. }
  185. catch (Exception e)
  186. {
  187. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  188. }
  189. };
  190. cancellationToken.Register(() => this.requestCallback.Remove(rpcId));
  191. request.RpcId = rpcId;
  192. this.Send(0x00, request);
  193. return tcs.Task;
  194. }
  195. public void Send(IMessage message)
  196. {
  197. this.Send(0x00, message);
  198. }
  199. public void Reply(IResponse message)
  200. {
  201. if (this.IsDisposed)
  202. {
  203. throw new Exception("session已经被Dispose了");
  204. }
  205. this.Send(0x01, message);
  206. }
  207. public void Send(byte flag, IMessage message)
  208. {
  209. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  210. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  211. byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(message);
  212. Send(flag, opcode, bytes);
  213. }
  214. public void Send(byte flag, ushort opcode, byte[] bytes)
  215. {
  216. if (this.IsDisposed)
  217. {
  218. throw new Exception("session已经被Dispose了");
  219. }
  220. this.byteses[0][0] = flag;
  221. this.byteses[1] = BitConverter.GetBytes(opcode);
  222. this.byteses[2] = bytes;
  223. #if SERVER
  224. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  225. if (this.Network.AppType == AppType.AllServer)
  226. {
  227. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  228. this.pkt.Length = 0;
  229. ushort index = 0;
  230. foreach (var byts in byteses)
  231. {
  232. Array.Copy(byts, 0, this.pkt.Bytes, index, byts.Length);
  233. index += (ushort)byts.Length;
  234. }
  235. this.pkt.Length = index;
  236. session.Run(this.pkt);
  237. return;
  238. }
  239. #endif
  240. channel.Send(this.byteses);
  241. }
  242. #if SERVER
  243. private Packet pkt = new Packet(ushort.MaxValue);
  244. #endif
  245. }
  246. }