Session.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace ETModel
  9. {
  10. [ObjectSystem]
  11. public class SessionAwakeSystem : AwakeSystem<Session, AChannel>
  12. {
  13. public override void Awake(Session self, AChannel b)
  14. {
  15. self.Awake(b);
  16. }
  17. }
  18. public sealed class Session : Entity
  19. {
  20. private static int RpcId { get; set; }
  21. private AChannel channel;
  22. private readonly Dictionary<int, Action<IResponse>> requestCallback = new Dictionary<int, Action<IResponse>>();
  23. private readonly byte[] opcodeBytes = new byte[2];
  24. public NetworkComponent Network
  25. {
  26. get
  27. {
  28. return this.GetParent<NetworkComponent>();
  29. }
  30. }
  31. public int Error
  32. {
  33. get
  34. {
  35. return this.channel.Error;
  36. }
  37. set
  38. {
  39. this.channel.Error = value;
  40. }
  41. }
  42. public void Awake(AChannel aChannel)
  43. {
  44. this.channel = aChannel;
  45. this.requestCallback.Clear();
  46. long id = this.Id;
  47. channel.ErrorCallback += (c, e) =>
  48. {
  49. this.Network.Remove(id);
  50. };
  51. channel.ReadCallback += this.OnRead;
  52. }
  53. public override void Dispose()
  54. {
  55. if (this.IsDisposed)
  56. {
  57. return;
  58. }
  59. this.Network.Remove(this.Id);
  60. base.Dispose();
  61. foreach (Action<IResponse> action in this.requestCallback.Values.ToArray())
  62. {
  63. action.Invoke(new ResponseMessage { Error = this.Error });
  64. }
  65. //int error = this.channel.Error;
  66. //if (this.channel.Error != 0)
  67. //{
  68. // Log.Trace($"session dispose: {this.Id} ErrorCode: {error}, please see ErrorCode.cs!");
  69. //}
  70. this.channel.Dispose();
  71. this.requestCallback.Clear();
  72. }
  73. public void Start()
  74. {
  75. this.channel.Start();
  76. }
  77. public IPEndPoint RemoteAddress
  78. {
  79. get
  80. {
  81. return this.channel.RemoteAddress;
  82. }
  83. }
  84. public ChannelType ChannelType
  85. {
  86. get
  87. {
  88. return this.channel.ChannelType;
  89. }
  90. }
  91. public MemoryStream Stream
  92. {
  93. get
  94. {
  95. return this.channel.Stream;
  96. }
  97. }
  98. public void OnRead(MemoryStream memoryStream)
  99. {
  100. try
  101. {
  102. this.Run(memoryStream);
  103. }
  104. catch (Exception e)
  105. {
  106. Log.Error(e);
  107. }
  108. }
  109. private void Run(MemoryStream memoryStream)
  110. {
  111. memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  112. ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);
  113. #if !SERVER
  114. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  115. {
  116. this.GetComponent<SessionCallbackComponent>().MessageCallback.Invoke(this, opcode, memoryStream);
  117. return;
  118. }
  119. #endif
  120. object message;
  121. try
  122. {
  123. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  124. object instance = opcodeTypeComponent.GetInstance(opcode);
  125. message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);
  126. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  127. {
  128. Log.Msg(message);
  129. }
  130. }
  131. catch (Exception e)
  132. {
  133. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  134. Log.Error($"opcode: {opcode} {this.Network.Count} {e}, ip: {this.RemoteAddress}");
  135. this.Error = ErrorCode.ERR_PacketParserError;
  136. this.Network.Remove(this.Id);
  137. return;
  138. }
  139. if (!(message is IResponse response))
  140. {
  141. this.Network.MessageDispatcher.Dispatch(this, opcode, message);
  142. return;
  143. }
  144. Action<IResponse> action;
  145. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  146. {
  147. throw new Exception($"not found rpc, response message: {StringHelper.MessageToStr(response)}");
  148. }
  149. this.requestCallback.Remove(response.RpcId);
  150. action(response);
  151. }
  152. public ETTask<IResponse> Call(IRequest request)
  153. {
  154. int rpcId = ++RpcId;
  155. var tcs = new ETTaskCompletionSource<IResponse>();
  156. this.requestCallback[rpcId] = (response) =>
  157. {
  158. try
  159. {
  160. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  161. {
  162. throw new RpcException(response.Error, response.Message);
  163. }
  164. tcs.SetResult(response);
  165. }
  166. catch (Exception e)
  167. {
  168. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  169. }
  170. };
  171. request.RpcId = rpcId;
  172. this.Send(request);
  173. return tcs.Task;
  174. }
  175. public ETTask<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  176. {
  177. int rpcId = ++RpcId;
  178. var tcs = new ETTaskCompletionSource<IResponse>();
  179. this.requestCallback[rpcId] = (response) =>
  180. {
  181. try
  182. {
  183. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  184. {
  185. throw new RpcException(response.Error, response.Message);
  186. }
  187. tcs.SetResult(response);
  188. }
  189. catch (Exception e)
  190. {
  191. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  192. }
  193. };
  194. cancellationToken.Register(() => this.requestCallback.Remove(rpcId));
  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. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  210. ushort opcode = opcodeTypeComponent.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. if (OpcodeHelper.IsNeedDebugLogMessage(opcode) )
  220. {
  221. #if !SERVER
  222. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  223. {
  224. }
  225. else
  226. #endif
  227. {
  228. Log.Msg(message);
  229. }
  230. }
  231. MemoryStream stream = this.Stream;
  232. stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  233. stream.SetLength(Packet.MessageIndex);
  234. this.Network.MessagePacker.SerializeTo(message, stream);
  235. stream.Seek(0, SeekOrigin.Begin);
  236. opcodeBytes.WriteTo(0, opcode);
  237. Array.Copy(opcodeBytes, 0, stream.GetBuffer(), 0, opcodeBytes.Length);
  238. #if SERVER
  239. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  240. if (this.Network.AppType == AppType.AllServer)
  241. {
  242. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  243. session.Run(stream);
  244. return;
  245. }
  246. #endif
  247. this.Send(stream);
  248. }
  249. public void Send(MemoryStream stream)
  250. {
  251. channel.Send(stream);
  252. }
  253. }
  254. }