Session.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace ETModel
  10. {
  11. [ObjectSystem]
  12. public class SessionAwakeSystem : AwakeSystem<Session, AChannel>
  13. {
  14. public override void Awake(Session self, AChannel b)
  15. {
  16. self.Awake(b);
  17. }
  18. }
  19. public sealed class Session : Entity
  20. {
  21. private static int RpcId { get; set; }
  22. private AChannel channel;
  23. public int Error;
  24. private readonly Dictionary<int, Action<IResponse>> requestCallback = new Dictionary<int, Action<IResponse>>();
  25. private readonly List<byte[]> byteses = new List<byte[]>() { new byte[1], new byte[0], new byte[0]};
  26. public NetworkComponent Network
  27. {
  28. get
  29. {
  30. return this.GetParent<NetworkComponent>();
  31. }
  32. }
  33. public void Awake(AChannel aChannel)
  34. {
  35. this.Error = 0;
  36. this.channel = aChannel;
  37. this.requestCallback.Clear();
  38. long id = this.Id;
  39. channel.ErrorCallback += (c, e) =>
  40. {
  41. this.Error = e;
  42. this.Network.Remove(id);
  43. };
  44. channel.ReadCallback += this.OnRead;
  45. this.channel.Start();
  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 = this.Error });
  58. }
  59. if (this.Error != 0)
  60. {
  61. Log.Error($"session dispose: {this.Id} {this.Error}");
  62. }
  63. this.Error = 0;
  64. this.channel.Dispose();
  65. this.Network.Remove(id);
  66. this.requestCallback.Clear();
  67. }
  68. public IPEndPoint RemoteAddress
  69. {
  70. get
  71. {
  72. return this.channel.RemoteAddress;
  73. }
  74. }
  75. public ChannelType ChannelType
  76. {
  77. get
  78. {
  79. return this.channel.ChannelType;
  80. }
  81. }
  82. public void OnRead(Packet packet)
  83. {
  84. try
  85. {
  86. this.Run(packet);
  87. }
  88. catch (Exception e)
  89. {
  90. Log.Error(e);
  91. }
  92. }
  93. private void Run(Packet packet)
  94. {
  95. byte flag = packet.Flag;
  96. ushort opcode = packet.Opcode;
  97. #if !SERVER
  98. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  99. {
  100. this.Network.MessageDispatcher.Dispatch(this, packet);
  101. return;
  102. }
  103. #endif
  104. // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
  105. if ((flag & 0x01) == 0)
  106. {
  107. this.Network.MessageDispatcher.Dispatch(this, packet);
  108. return;
  109. }
  110. object message;
  111. try
  112. {
  113. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  114. Type responseType = opcodeTypeComponent.GetType(opcode);
  115. message = this.Network.MessagePacker.DeserializeFrom(responseType, packet.Stream);
  116. //Log.Debug($"recv: {JsonHelper.ToJson(message)}");
  117. }
  118. catch (Exception e)
  119. {
  120. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  121. Log.Error($"opcode: {opcode} {this.Network.Count} {e} ");
  122. this.Error = ErrorCode.ERR_PacketParserError;
  123. this.Network.Remove(this.Id);
  124. return;
  125. }
  126. IResponse response = message as IResponse;
  127. if (response == null)
  128. {
  129. throw new Exception($"flag is response, but message is not! {opcode}");
  130. }
  131. Action<IResponse> action;
  132. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  133. {
  134. return;
  135. }
  136. this.requestCallback.Remove(response.RpcId);
  137. action(response);
  138. }
  139. public Task<IResponse> Call(IRequest request)
  140. {
  141. int rpcId = ++RpcId;
  142. var tcs = new TaskCompletionSource<IResponse>();
  143. this.requestCallback[rpcId] = (response) =>
  144. {
  145. try
  146. {
  147. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  148. {
  149. throw new RpcException(response.Error, response.Message);
  150. }
  151. tcs.SetResult(response);
  152. }
  153. catch (Exception e)
  154. {
  155. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  156. }
  157. };
  158. request.RpcId = rpcId;
  159. this.Send(0x00, request);
  160. return tcs.Task;
  161. }
  162. public Task<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  163. {
  164. int rpcId = ++RpcId;
  165. var tcs = new TaskCompletionSource<IResponse>();
  166. this.requestCallback[rpcId] = (response) =>
  167. {
  168. try
  169. {
  170. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  171. {
  172. throw new RpcException(response.Error, response.Message);
  173. }
  174. tcs.SetResult(response);
  175. }
  176. catch (Exception e)
  177. {
  178. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  179. }
  180. };
  181. cancellationToken.Register(() => this.requestCallback.Remove(rpcId));
  182. request.RpcId = rpcId;
  183. this.Send(0x00, request);
  184. return tcs.Task;
  185. }
  186. public void Send(IMessage message)
  187. {
  188. this.Send(0x00, message);
  189. }
  190. public void Reply(IResponse message)
  191. {
  192. if (this.IsDisposed)
  193. {
  194. throw new Exception("session已经被Dispose了");
  195. }
  196. this.Send(0x01, message);
  197. }
  198. public void Send(byte flag, IMessage message)
  199. {
  200. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  201. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  202. byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(message);
  203. Send(flag, opcode, bytes);
  204. }
  205. public void Send(byte flag, ushort opcode, byte[] bytes)
  206. {
  207. if (this.IsDisposed)
  208. {
  209. throw new Exception("session已经被Dispose了");
  210. }
  211. this.byteses[0][0] = flag;
  212. this.byteses[1] = BitConverter.GetBytes(opcode);
  213. this.byteses[2] = bytes;
  214. #if SERVER
  215. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  216. if (this.Network.AppType == AppType.AllServer)
  217. {
  218. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  219. Packet packet = ((TChannel)this.channel).parser.packet;
  220. packet.Flag = flag;
  221. packet.Opcode = opcode;
  222. packet.Stream.Seek(0, SeekOrigin.Begin);
  223. packet.Stream.SetLength(bytes.Length);
  224. Array.Copy(bytes, 0, packet.Bytes, 0, bytes.Length);
  225. session.Run(packet);
  226. return;
  227. }
  228. #endif
  229. channel.Send(this.byteses);
  230. }
  231. }
  232. }