Session.cs 5.9 KB

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