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