Session.cs 5.9 KB

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