Session.cs 6.9 KB

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