Session.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. namespace ETModel
  8. {
  9. [ObjectSystem]
  10. public class SessionAwakeSystem : AwakeSystem<Session, AChannel>
  11. {
  12. public override void Awake(Session self, AChannel b)
  13. {
  14. self.Awake(b);
  15. }
  16. }
  17. public sealed class Session : Entity
  18. {
  19. private static int RpcId { get; set; }
  20. private AChannel channel;
  21. private readonly Dictionary<int, Action<IResponse>> requestCallback = new Dictionary<int, Action<IResponse>>();
  22. private readonly List<byte[]> byteses = new List<byte[]>() { new byte[1], new byte[2] };
  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. this.channel = aChannel;
  44. this.channel.Parent = this;
  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. long id = 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.Network.Remove(id);
  72. this.requestCallback.Clear();
  73. }
  74. public void Start()
  75. {
  76. this.channel.Start();
  77. }
  78. public IPEndPoint RemoteAddress
  79. {
  80. get
  81. {
  82. return this.channel.RemoteAddress;
  83. }
  84. }
  85. public ChannelType ChannelType
  86. {
  87. get
  88. {
  89. return this.channel.ChannelType;
  90. }
  91. }
  92. public MemoryStream Stream
  93. {
  94. get
  95. {
  96. return this.channel.Stream;
  97. }
  98. }
  99. public void OnRead(MemoryStream memoryStream)
  100. {
  101. try
  102. {
  103. this.Run(memoryStream);
  104. }
  105. catch (Exception e)
  106. {
  107. Log.Error(e);
  108. }
  109. }
  110. private void Run(MemoryStream memoryStream)
  111. {
  112. memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  113. byte flag = memoryStream.GetBuffer()[Packet.FlagIndex];
  114. ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);
  115. #if !SERVER
  116. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  117. {
  118. this.GetComponent<SessionCallbackComponent>().MessageCallback.Invoke(this, flag, opcode, memoryStream);
  119. return;
  120. }
  121. #endif
  122. object message;
  123. try
  124. {
  125. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  126. object instance = opcodeTypeComponent.GetInstance(opcode);
  127. message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);
  128. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  129. {
  130. Log.Msg(message);
  131. }
  132. }
  133. catch (Exception e)
  134. {
  135. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  136. Log.Error($"opcode: {opcode} {this.Network.Count} {e} ");
  137. this.Error = ErrorCode.ERR_PacketParserError;
  138. this.Network.Remove(this.Id);
  139. return;
  140. }
  141. // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
  142. if ((flag & 0x01) == 0)
  143. {
  144. this.Network.MessageDispatcher.Dispatch(this, opcode, message);
  145. return;
  146. }
  147. IResponse response = message as IResponse;
  148. if (response == null)
  149. {
  150. throw new Exception($"flag is response, but message is not! {opcode}");
  151. }
  152. Action<IResponse> action;
  153. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  154. {
  155. return;
  156. }
  157. this.requestCallback.Remove(response.RpcId);
  158. action(response);
  159. }
  160. public ETTask<IResponse> Call(IRequest request)
  161. {
  162. int rpcId = ++RpcId;
  163. var tcs = new ETTaskCompletionSource<IResponse>();
  164. this.requestCallback[rpcId] = (response) =>
  165. {
  166. try
  167. {
  168. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  169. {
  170. throw new RpcException(response.Error, response.Message);
  171. }
  172. tcs.TrySetResult(response);
  173. }
  174. catch (Exception e)
  175. {
  176. tcs.TrySetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  177. }
  178. };
  179. request.RpcId = rpcId;
  180. this.Send(0x00, request);
  181. return tcs.Task;
  182. }
  183. public ETTask<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  184. {
  185. int rpcId = ++RpcId;
  186. var tcs = new ETTaskCompletionSource<IResponse>();
  187. this.requestCallback[rpcId] = (response) =>
  188. {
  189. try
  190. {
  191. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  192. {
  193. throw new RpcException(response.Error, response.Message);
  194. }
  195. tcs.SetResult(response);
  196. }
  197. catch (Exception e)
  198. {
  199. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  200. }
  201. };
  202. cancellationToken.Register(() => this.requestCallback.Remove(rpcId));
  203. request.RpcId = rpcId;
  204. this.Send(0x00, request);
  205. return tcs.Task;
  206. }
  207. public void Send(IMessage message)
  208. {
  209. this.Send(0x00, message);
  210. }
  211. public void Reply(IResponse message)
  212. {
  213. if (this.IsDisposed)
  214. {
  215. throw new Exception("session已经被Dispose了");
  216. }
  217. this.Send(0x01, message);
  218. }
  219. public void Send(byte flag, IMessage message)
  220. {
  221. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  222. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  223. Send(flag, opcode, message);
  224. }
  225. public void Send(byte flag, ushort opcode, object message)
  226. {
  227. if (this.IsDisposed)
  228. {
  229. throw new Exception("session已经被Dispose了");
  230. }
  231. if (OpcodeHelper.IsNeedDebugLogMessage(opcode) )
  232. {
  233. #if !SERVER
  234. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  235. {
  236. }
  237. else
  238. #endif
  239. {
  240. Log.Msg(message);
  241. }
  242. }
  243. MemoryStream stream = this.Stream;
  244. stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  245. stream.SetLength(Packet.MessageIndex);
  246. this.Network.MessagePacker.SerializeTo(message, stream);
  247. stream.Seek(0, SeekOrigin.Begin);
  248. if (stream.Length > ushort.MaxValue)
  249. {
  250. Log.Error($"message too large: {stream.Length}, opcode: {opcode}");
  251. return;
  252. }
  253. this.byteses[0][0] = flag;
  254. this.byteses[1].WriteTo(0, opcode);
  255. int index = 0;
  256. foreach (var bytes in this.byteses)
  257. {
  258. Array.Copy(bytes, 0, stream.GetBuffer(), index, bytes.Length);
  259. index += bytes.Length;
  260. }
  261. #if SERVER
  262. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  263. if (this.Network.AppType == AppType.AllServer)
  264. {
  265. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  266. session.Run(stream);
  267. return;
  268. }
  269. #endif
  270. this.Send(stream);
  271. }
  272. public void Send(MemoryStream stream)
  273. {
  274. channel.Send(stream);
  275. }
  276. }
  277. }