Session.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. object message;
  111. try
  112. {
  113. Type type = OpcodeTypeComponent.Instance.GetType(opcode);
  114. message = MessagePackHelper.DeserializeFrom(opcode, type, memoryStream);
  115. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  116. {
  117. Log.Msg(message);
  118. }
  119. }
  120. catch (Exception e)
  121. {
  122. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  123. Log.Error($"opcode: {opcode} {this.Network.Count} {e}, ip: {this.RemoteAddress}");
  124. this.Error = ErrorCode.ERR_PacketParserError;
  125. this.Network.Remove(this.Id);
  126. return;
  127. }
  128. RunMessage(opcode, message);
  129. }
  130. private void RunMessage(ushort opcode, object message)
  131. {
  132. this.LastRecvTime = TimeHelper.Now();
  133. if (!(message is IResponse response))
  134. {
  135. this.Network.MessageDispatcher.Dispatch(this, opcode, message);
  136. return;
  137. }
  138. #if SERVER
  139. if (message is IActorResponse)
  140. {
  141. this.Network.MessageDispatcher.Dispatch(this, opcode, message);
  142. return;
  143. }
  144. #endif
  145. Action<IResponse> action;
  146. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  147. {
  148. throw new Exception($"not found rpc, response message: {StringHelper.MessageToStr(response)}");
  149. }
  150. this.requestCallback.Remove(response.RpcId);
  151. action(response);
  152. }
  153. public ETTask<IResponse> CallWithoutException(IRequest request)
  154. {
  155. int rpcId = ++RpcId;
  156. var tcs = new ETTaskCompletionSource<IResponse>();
  157. this.requestCallback[rpcId] = (response) =>
  158. {
  159. if (response is ErrorResponse)
  160. {
  161. tcs.SetException(new Exception($"Rpc error: {MongoHelper.ToJson(response)}"));
  162. return;
  163. }
  164. tcs.SetResult(response);
  165. };
  166. request.RpcId = rpcId;
  167. this.Send(request);
  168. return tcs.Task;
  169. }
  170. public ETTask<IResponse> Call(IRequest request)
  171. {
  172. int rpcId = ++RpcId;
  173. var tcs = new ETTaskCompletionSource<IResponse>();
  174. this.requestCallback[rpcId] = (response) =>
  175. {
  176. if (response is ErrorResponse)
  177. {
  178. tcs.SetException(new Exception($"Rpc error: {MongoHelper.ToJson(response)}"));
  179. return;
  180. }
  181. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  182. {
  183. tcs.SetException(new Exception($"Rpc error: {MongoHelper.ToJson(response)}"));
  184. return;
  185. }
  186. tcs.SetResult(response);
  187. };
  188. request.RpcId = rpcId;
  189. this.Send(request);
  190. return tcs.Task;
  191. }
  192. public void Reply(IResponse message)
  193. {
  194. if (this.IsDisposed)
  195. {
  196. throw new Exception("session已经被Dispose了");
  197. }
  198. this.Send(message);
  199. }
  200. public void Send(IMessage message)
  201. {
  202. ushort opcode = OpcodeTypeComponent.Instance.GetOpcode(message.GetType());
  203. Send(opcode, message);
  204. }
  205. public void Send(ushort opcode, object message)
  206. {
  207. if (this.IsDisposed)
  208. {
  209. throw new Exception("session已经被Dispose了");
  210. }
  211. this.LastSendTime = TimeHelper.Now();
  212. if (OpcodeHelper.IsNeedDebugLogMessage(opcode) )
  213. {
  214. Log.Msg(message);
  215. }
  216. MemoryStream stream = this.Stream;
  217. stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  218. stream.SetLength(Packet.MessageIndex);
  219. MessagePackHelper.SerializeTo(opcode, message, stream);
  220. stream.Seek(0, SeekOrigin.Begin);
  221. opcodeBytes.WriteTo(0, opcode);
  222. Array.Copy(opcodeBytes, 0, stream.GetBuffer(), 0, opcodeBytes.Length);
  223. this.Send(stream);
  224. }
  225. public void Send(MemoryStream stream)
  226. {
  227. channel.Send(stream);
  228. }
  229. }
  230. }