Session.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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[2], 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. this.channel.Start();
  54. }
  55. public override void Dispose()
  56. {
  57. if (this.IsDisposed)
  58. {
  59. return;
  60. }
  61. long id = this.Id;
  62. base.Dispose();
  63. foreach (Action<IResponse> action in this.requestCallback.Values.ToArray())
  64. {
  65. action.Invoke(new ResponseMessage { Error = this.Error });
  66. }
  67. int error = this.channel.Error;
  68. if (this.channel.Error != 0)
  69. {
  70. Log.Error($"session dispose: {this.Id} {error}");
  71. }
  72. this.channel.Dispose();
  73. this.Network.Remove(id);
  74. this.requestCallback.Clear();
  75. }
  76. public IPEndPoint RemoteAddress
  77. {
  78. get
  79. {
  80. return this.channel.RemoteAddress;
  81. }
  82. }
  83. public ChannelType ChannelType
  84. {
  85. get
  86. {
  87. return this.channel.ChannelType;
  88. }
  89. }
  90. public MemoryStream Stream
  91. {
  92. get
  93. {
  94. return this.channel.Stream;
  95. }
  96. }
  97. public void OnRead(Packet packet)
  98. {
  99. try
  100. {
  101. this.Run(packet);
  102. }
  103. catch (Exception e)
  104. {
  105. Log.Error(e);
  106. }
  107. }
  108. private void Run(Packet packet)
  109. {
  110. packet.Flag = packet.Bytes[Packet.FlagIndex];
  111. packet.Opcode = BitConverter.ToUInt16(packet.Bytes, Packet.OpcodeIndex);
  112. packet.Stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  113. byte flag = packet.Flag;
  114. ushort opcode = packet.Opcode;
  115. #if !SERVER
  116. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  117. {
  118. this.Network.MessageDispatcher.Dispatch(this, packet);
  119. return;
  120. }
  121. #endif
  122. // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
  123. if ((flag & 0x01) == 0)
  124. {
  125. this.Network.MessageDispatcher.Dispatch(this, packet);
  126. return;
  127. }
  128. object message;
  129. try
  130. {
  131. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  132. object instance = opcodeTypeComponent.GetInstance(opcode);
  133. message = this.Network.MessagePacker.DeserializeFrom(instance, packet.Stream);
  134. //Log.Debug($"recv: {JsonHelper.ToJson(message)}");
  135. }
  136. catch (Exception e)
  137. {
  138. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  139. Log.Error($"opcode: {opcode} {this.Network.Count} {e} ");
  140. this.Error = ErrorCode.ERR_PacketParserError;
  141. this.Network.Remove(this.Id);
  142. return;
  143. }
  144. IResponse response = message as IResponse;
  145. if (response == null)
  146. {
  147. throw new Exception($"flag is response, but message is not! {opcode}");
  148. }
  149. Action<IResponse> action;
  150. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  151. {
  152. return;
  153. }
  154. this.requestCallback.Remove(response.RpcId);
  155. action(response);
  156. }
  157. public Task<IResponse> Call(IRequest request)
  158. {
  159. int rpcId = ++RpcId;
  160. var tcs = new TaskCompletionSource<IResponse>();
  161. this.requestCallback[rpcId] = (response) =>
  162. {
  163. try
  164. {
  165. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  166. {
  167. throw new RpcException(response.Error, response.Message);
  168. }
  169. tcs.SetResult(response);
  170. }
  171. catch (Exception e)
  172. {
  173. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  174. }
  175. };
  176. request.RpcId = rpcId;
  177. this.Send(0x00, request);
  178. return tcs.Task;
  179. }
  180. public Task<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  181. {
  182. int rpcId = ++RpcId;
  183. var tcs = new TaskCompletionSource<IResponse>();
  184. this.requestCallback[rpcId] = (response) =>
  185. {
  186. try
  187. {
  188. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  189. {
  190. throw new RpcException(response.Error, response.Message);
  191. }
  192. tcs.SetResult(response);
  193. }
  194. catch (Exception e)
  195. {
  196. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  197. }
  198. };
  199. cancellationToken.Register(() => this.requestCallback.Remove(rpcId));
  200. request.RpcId = rpcId;
  201. this.Send(0x00, request);
  202. return tcs.Task;
  203. }
  204. public void Send(IMessage message)
  205. {
  206. this.Send(0x00, message);
  207. }
  208. public void Reply(IResponse message)
  209. {
  210. if (this.IsDisposed)
  211. {
  212. throw new Exception("session已经被Dispose了");
  213. }
  214. this.Send(0x01, message);
  215. }
  216. public void Send(byte flag, IMessage message)
  217. {
  218. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  219. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  220. Send(flag, opcode, message);
  221. }
  222. public void Send(byte flag, ushort opcode, object message)
  223. {
  224. if (this.IsDisposed)
  225. {
  226. throw new Exception("session已经被Dispose了");
  227. }
  228. MemoryStream stream = this.Stream;
  229. stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  230. stream.SetLength(Packet.MessageIndex);
  231. this.Network.MessagePacker.SerializeTo(message, stream);
  232. stream.Seek(0, SeekOrigin.Begin);
  233. ushort size = (ushort)(stream.Length - Packet.SizeLength);
  234. this.byteses[0].WriteTo(0, size);
  235. this.byteses[1][0] = flag;
  236. this.byteses[2].WriteTo(0, opcode);
  237. int index = 0;
  238. foreach (var bytes in this.byteses)
  239. {
  240. Array.Copy(bytes, 0, stream.GetBuffer(), index, bytes.Length);
  241. index += bytes.Length;
  242. }
  243. #if SERVER
  244. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  245. if (this.Network.AppType == AppType.AllServer)
  246. {
  247. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  248. Packet packet = ((TChannel)this.channel).parser.packet;
  249. session.Run(packet);
  250. return;
  251. }
  252. #endif
  253. this.Send(stream);
  254. }
  255. public void Send(MemoryStream stream)
  256. {
  257. channel.Send(stream);
  258. }
  259. }
  260. }