Session.cs 6.1 KB

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