Session.cs 6.2 KB

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