Session.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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.ToString());
  97. continue;
  98. }
  99. try
  100. {
  101. this.Run(packet);
  102. }
  103. catch (Exception e)
  104. {
  105. Log.Error(e.ToString());
  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 (OpcodeHelper.IsClientHotfixMessage(opcode))
  120. {
  121. this.Network.MessageDispatcher.Dispatch(this, packet);
  122. return;
  123. }
  124. // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
  125. if ((flag & 0x01) == 0)
  126. {
  127. this.Network.MessageDispatcher.Dispatch(this, packet);
  128. return;
  129. }
  130. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  131. Type responseType = opcodeTypeComponent.GetType(opcode);
  132. object message = this.Network.MessagePacker.DeserializeFrom(responseType, packet.Bytes, Packet.Index, packet.Length - Packet.Index);
  133. IResponse response = message as IResponse;
  134. if (response == null)
  135. {
  136. throw new Exception($"flag is response, but message is not! {opcode}");
  137. }
  138. Action<IResponse> action;
  139. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  140. {
  141. return;
  142. }
  143. this.requestCallback.Remove(response.RpcId);
  144. action(response);
  145. }
  146. public Task<IResponse> Call(IRequest request)
  147. {
  148. int rpcId = ++RpcId;
  149. var tcs = new TaskCompletionSource<IResponse>();
  150. this.requestCallback[rpcId] = (response) =>
  151. {
  152. try
  153. {
  154. if (response.Error > ErrorCode.ERR_Exception)
  155. {
  156. throw new RpcException(response.Error, response.Message);
  157. }
  158. tcs.SetResult(response);
  159. }
  160. catch (Exception e)
  161. {
  162. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  163. }
  164. };
  165. request.RpcId = rpcId;
  166. this.Send(0x00, request);
  167. return tcs.Task;
  168. }
  169. public Task<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  170. {
  171. int rpcId = ++RpcId;
  172. var tcs = new TaskCompletionSource<IResponse>();
  173. this.requestCallback[rpcId] = (response) =>
  174. {
  175. try
  176. {
  177. if (response.Error > ErrorCode.ERR_Exception)
  178. {
  179. throw new RpcException(response.Error, response.Message);
  180. }
  181. tcs.SetResult(response);
  182. }
  183. catch (Exception e)
  184. {
  185. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  186. }
  187. };
  188. cancellationToken.Register(() => this.requestCallback.Remove(rpcId));
  189. request.RpcId = rpcId;
  190. this.Send(0x00, request);
  191. return tcs.Task;
  192. }
  193. public void Send(IMessage message)
  194. {
  195. this.Send(0x00, message);
  196. }
  197. public void Reply(IResponse message)
  198. {
  199. if (this.IsDisposed)
  200. {
  201. throw new Exception("session已经被Dispose了");
  202. }
  203. this.Send(0x01, message);
  204. }
  205. public void Send(byte flag, object message)
  206. {
  207. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  208. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  209. byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(message);
  210. Send(flag, opcode, bytes);
  211. }
  212. public void Send(byte flag, ushort opcode, byte[] bytes)
  213. {
  214. if (this.IsDisposed)
  215. {
  216. throw new Exception("session已经被Dispose了");
  217. }
  218. this.byteses[0][0] = flag;
  219. this.byteses[1] = BitConverter.GetBytes(opcode);
  220. this.byteses[2] = bytes;
  221. #if SERVER
  222. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  223. if (this.Network.AppType == AppType.AllServer)
  224. {
  225. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  226. this.pkt.Length = 0;
  227. ushort index = 0;
  228. foreach (var byts in byteses)
  229. {
  230. Array.Copy(byts, 0, this.pkt.Bytes, index, byts.Length);
  231. index += (ushort)byts.Length;
  232. }
  233. this.pkt.Length = index;
  234. session.Run(this.pkt);
  235. return;
  236. }
  237. #endif
  238. channel.Send(this.byteses);
  239. }
  240. #if SERVER
  241. private Packet pkt = new Packet(ushort.MaxValue);
  242. #endif
  243. }
  244. }