Session.cs 5.8 KB

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