Session.cs 6.9 KB

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