Session.cs 6.4 KB

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