Session.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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} ");
  135. this.Error = ErrorCode.ERR_PacketParserError;
  136. this.Network.Remove(this.Id);
  137. return;
  138. }
  139. IResponse response = message as IResponse;
  140. if (response == null)
  141. {
  142. this.Network.MessageDispatcher.Dispatch(this, opcode, message);
  143. return;
  144. }
  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> Call(IRequest request)
  154. {
  155. int rpcId = ++RpcId;
  156. var tcs = new ETTaskCompletionSource<IResponse>();
  157. this.requestCallback[rpcId] = (response) =>
  158. {
  159. try
  160. {
  161. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  162. {
  163. throw new RpcException(response.Error, response.Message);
  164. }
  165. tcs.SetResult(response);
  166. }
  167. catch (Exception e)
  168. {
  169. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  170. }
  171. };
  172. request.RpcId = rpcId;
  173. this.Send(request);
  174. return tcs.Task;
  175. }
  176. public ETTask<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  177. {
  178. int rpcId = ++RpcId;
  179. var tcs = new ETTaskCompletionSource<IResponse>();
  180. this.requestCallback[rpcId] = (response) =>
  181. {
  182. try
  183. {
  184. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  185. {
  186. throw new RpcException(response.Error, response.Message);
  187. }
  188. tcs.SetResult(response);
  189. }
  190. catch (Exception e)
  191. {
  192. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  193. }
  194. };
  195. cancellationToken.Register(() => this.requestCallback.Remove(rpcId));
  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. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  211. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  212. Send(opcode, message);
  213. }
  214. public void Send(ushort opcode, object message)
  215. {
  216. if (this.IsDisposed)
  217. {
  218. throw new Exception("session已经被Dispose了");
  219. }
  220. if (OpcodeHelper.IsNeedDebugLogMessage(opcode) )
  221. {
  222. #if !SERVER
  223. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  224. {
  225. }
  226. else
  227. #endif
  228. {
  229. Log.Msg(message);
  230. }
  231. }
  232. MemoryStream stream = this.Stream;
  233. stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  234. stream.SetLength(Packet.MessageIndex);
  235. this.Network.MessagePacker.SerializeTo(message, stream);
  236. stream.Seek(0, SeekOrigin.Begin);
  237. opcodeBytes.WriteTo(0, opcode);
  238. Array.Copy(opcodeBytes, 0, stream.GetBuffer(), 0, opcodeBytes.Length);
  239. #if SERVER
  240. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  241. if (this.Network.AppType == AppType.AllServer)
  242. {
  243. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  244. session.Run(stream);
  245. return;
  246. }
  247. #endif
  248. this.Send(stream);
  249. }
  250. public void Send(MemoryStream stream)
  251. {
  252. channel.Send(stream);
  253. }
  254. }
  255. }