Session.cs 6.1 KB

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