Session.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace ETModel
  6. {
  7. [ObjectSystem]
  8. public class SessionAwakeSystem : AwakeSystem<Session, AChannel>
  9. {
  10. public override void Awake(Session self, AChannel b)
  11. {
  12. self.Awake(b);
  13. }
  14. }
  15. public sealed class Session : Entity
  16. {
  17. private static int RpcId { get; set; }
  18. private AChannel channel;
  19. private readonly Dictionary<int, Action<IResponse>> requestCallback = new Dictionary<int, Action<IResponse>>();
  20. private readonly byte[] opcodeBytes = new byte[2];
  21. public long LastRecvTime { get; private set; }
  22. public long LastSendTime { get; private set; }
  23. public NetworkComponent Network
  24. {
  25. get
  26. {
  27. return this.GetParent<NetworkComponent>();
  28. }
  29. }
  30. public int Error
  31. {
  32. get
  33. {
  34. return this.channel.Error;
  35. }
  36. set
  37. {
  38. this.channel.Error = value;
  39. }
  40. }
  41. public void Awake(AChannel aChannel)
  42. {
  43. long timeNow = TimeHelper.Now();
  44. this.LastRecvTime = timeNow;
  45. this.LastSendTime = timeNow;
  46. this.channel = aChannel;
  47. this.requestCallback.Clear();
  48. long id = this.Id;
  49. channel.ErrorCallback += (c, e) =>
  50. {
  51. this.Network.Remove(id);
  52. };
  53. channel.ReadCallback += this.OnRead;
  54. }
  55. public override void Dispose()
  56. {
  57. if (this.IsDisposed)
  58. {
  59. return;
  60. }
  61. this.Network.Remove(this.Id);
  62. base.Dispose();
  63. foreach (Action<IResponse> action in this.requestCallback.Values.ToArray())
  64. {
  65. action.Invoke(new ErrorResponse { Error = this.Error });
  66. }
  67. int error = this.channel.Error;
  68. if (this.channel.Error != 0)
  69. {
  70. Log.Info($"session dispose: {this.Id} ErrorCode: {error}, please see ErrorCode.cs!");
  71. }
  72. this.channel.Dispose();
  73. this.requestCallback.Clear();
  74. }
  75. public string RemoteAddress
  76. {
  77. get
  78. {
  79. return this.channel.RemoteAddress;
  80. }
  81. }
  82. public ChannelType ChannelType
  83. {
  84. get
  85. {
  86. return this.channel.ChannelType;
  87. }
  88. }
  89. public MemoryStream Stream
  90. {
  91. get
  92. {
  93. return this.channel.Stream;
  94. }
  95. }
  96. public void OnRead(MemoryStream memoryStream)
  97. {
  98. try
  99. {
  100. this.Run(memoryStream);
  101. }
  102. catch (Exception e)
  103. {
  104. Log.Error(e);
  105. }
  106. }
  107. private void Run(MemoryStream memoryStream)
  108. {
  109. memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  110. ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);
  111. #if !SERVER
  112. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  113. {
  114. this.GetComponent<SessionCallbackComponent>().MessageCallback.Invoke(this, opcode, memoryStream);
  115. return;
  116. }
  117. #endif
  118. object message;
  119. try
  120. {
  121. object instance = OpcodeTypeComponent.Instance.GetInstance(opcode);
  122. message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);
  123. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  124. {
  125. Log.Msg(message);
  126. }
  127. }
  128. catch (Exception e)
  129. {
  130. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  131. Log.Error($"opcode: {opcode} {this.Network.Count} {e}, ip: {this.RemoteAddress}");
  132. this.Error = ErrorCode.ERR_PacketParserError;
  133. this.Network.Remove(this.Id);
  134. return;
  135. }
  136. RunMessage(opcode, message);
  137. }
  138. private void RunMessage(ushort opcode, object message)
  139. {
  140. this.LastRecvTime = TimeHelper.Now();
  141. if (!(message is IResponse response))
  142. {
  143. this.Network.MessageDispatcher.Dispatch(this, opcode, message);
  144. return;
  145. }
  146. #if SERVER
  147. if (message is IActorResponse)
  148. {
  149. this.Network.MessageDispatcher.Dispatch(this, opcode, message);
  150. return;
  151. }
  152. #endif
  153. Action<IResponse> action;
  154. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  155. {
  156. throw new Exception($"not found rpc, response message: {StringHelper.MessageToStr(response)}");
  157. }
  158. this.requestCallback.Remove(response.RpcId);
  159. action(response);
  160. }
  161. public ETTask<IResponse> CallWithoutException(IRequest request)
  162. {
  163. int rpcId = ++RpcId;
  164. var tcs = new ETTaskCompletionSource<IResponse>();
  165. this.requestCallback[rpcId] = (response) =>
  166. {
  167. if (response is ErrorResponse)
  168. {
  169. tcs.SetException(new Exception($"Rpc error: {MongoHelper.ToJson(response)}"));
  170. return;
  171. }
  172. tcs.SetResult(response);
  173. };
  174. request.RpcId = rpcId;
  175. this.Send(request);
  176. return tcs.Task;
  177. }
  178. public ETTask<IResponse> Call(IRequest request)
  179. {
  180. int rpcId = ++RpcId;
  181. var tcs = new ETTaskCompletionSource<IResponse>();
  182. this.requestCallback[rpcId] = (response) =>
  183. {
  184. if (response is ErrorResponse)
  185. {
  186. tcs.SetException(new Exception($"Rpc error: {MongoHelper.ToJson(response)}"));
  187. return;
  188. }
  189. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  190. {
  191. tcs.SetException(new Exception($"Rpc error: {MongoHelper.ToJson(response)}"));
  192. return;
  193. }
  194. tcs.SetResult(response);
  195. };
  196. request.RpcId = rpcId;
  197. this.Send(request);
  198. return tcs.Task;
  199. }
  200. public void Reply(IResponse message)
  201. {
  202. if (this.IsDisposed)
  203. {
  204. throw new Exception("session已经被Dispose了");
  205. }
  206. this.Send(message);
  207. }
  208. public void Send(IMessage message)
  209. {
  210. ushort opcode = OpcodeTypeComponent.Instance.GetOpcode(message.GetType());
  211. Send(opcode, message);
  212. }
  213. public void Send(ushort opcode, object message)
  214. {
  215. if (this.IsDisposed)
  216. {
  217. throw new Exception("session已经被Dispose了");
  218. }
  219. this.LastSendTime = TimeHelper.Now();
  220. if (OpcodeHelper.IsNeedDebugLogMessage(opcode) )
  221. {
  222. Log.Msg(message);
  223. }
  224. MemoryStream stream = this.Stream;
  225. stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  226. stream.SetLength(Packet.MessageIndex);
  227. this.Network.MessagePacker.SerializeTo(message, stream);
  228. stream.Seek(0, SeekOrigin.Begin);
  229. opcodeBytes.WriteTo(0, opcode);
  230. Array.Copy(opcodeBytes, 0, stream.GetBuffer(), 0, opcodeBytes.Length);
  231. this.Send(stream);
  232. }
  233. public void Send(MemoryStream stream)
  234. {
  235. channel.Send(stream);
  236. }
  237. }
  238. }