Session.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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[0] };
  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. byte flag = packet.Flag;
  111. ushort opcode = packet.Opcode;
  112. #if !SERVER
  113. if (OpcodeHelper.IsClientHotfixMessage(opcode))
  114. {
  115. this.Network.MessageDispatcher.Dispatch(this, packet);
  116. return;
  117. }
  118. #endif
  119. // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
  120. if ((flag & 0x01) == 0)
  121. {
  122. this.Network.MessageDispatcher.Dispatch(this, packet);
  123. return;
  124. }
  125. object message;
  126. try
  127. {
  128. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  129. object instance = opcodeTypeComponent.GetInstance(opcode);
  130. message = this.Network.MessagePacker.DeserializeFrom(instance, packet.Stream);
  131. //Log.Debug($"recv: {JsonHelper.ToJson(message)}");
  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. IResponse response = message as IResponse;
  142. if (response == null)
  143. {
  144. throw new Exception($"flag is response, but message is not! {opcode}");
  145. }
  146. Action<IResponse> action;
  147. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  148. {
  149. return;
  150. }
  151. this.requestCallback.Remove(response.RpcId);
  152. action(response);
  153. }
  154. public Task<IResponse> Call(IRequest request)
  155. {
  156. int rpcId = ++RpcId;
  157. var tcs = new TaskCompletionSource<IResponse>();
  158. this.requestCallback[rpcId] = (response) =>
  159. {
  160. try
  161. {
  162. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  163. {
  164. throw new RpcException(response.Error, response.Message);
  165. }
  166. tcs.SetResult(response);
  167. }
  168. catch (Exception e)
  169. {
  170. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  171. }
  172. };
  173. request.RpcId = rpcId;
  174. this.Send(0x00, request);
  175. return tcs.Task;
  176. }
  177. public Task<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  178. {
  179. int rpcId = ++RpcId;
  180. var tcs = new TaskCompletionSource<IResponse>();
  181. this.requestCallback[rpcId] = (response) =>
  182. {
  183. try
  184. {
  185. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  186. {
  187. throw new RpcException(response.Error, response.Message);
  188. }
  189. tcs.SetResult(response);
  190. }
  191. catch (Exception e)
  192. {
  193. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  194. }
  195. };
  196. cancellationToken.Register(() => this.requestCallback.Remove(rpcId));
  197. request.RpcId = rpcId;
  198. this.Send(0x00, request);
  199. return tcs.Task;
  200. }
  201. public void Send(IMessage message)
  202. {
  203. this.Send(0x00, message);
  204. }
  205. public void Reply(IResponse message)
  206. {
  207. if (this.IsDisposed)
  208. {
  209. throw new Exception("session已经被Dispose了");
  210. }
  211. this.Send(0x01, message);
  212. }
  213. public void Send(byte flag, IMessage message)
  214. {
  215. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  216. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  217. Send(flag, opcode, message);
  218. }
  219. public void Send(byte flag, ushort opcode, object message)
  220. {
  221. if (this.IsDisposed)
  222. {
  223. throw new Exception("session已经被Dispose了");
  224. }
  225. this.byteses[0][0] = flag;
  226. this.byteses[1] = BitConverter.GetBytes(opcode);
  227. MemoryStream stream = this.Stream;
  228. int index = Packet.Index;
  229. stream.Seek(index, SeekOrigin.Begin);
  230. stream.SetLength(index);
  231. var bb = this.Network.MessagePacker.SerializeTo(message);
  232. this.Network.MessagePacker.SerializeTo(message, stream);
  233. stream.Seek(0, SeekOrigin.Begin);
  234. index = 0;
  235. foreach (var bytes in this.byteses)
  236. {
  237. Array.Copy(bytes, 0, stream.GetBuffer(), index, bytes.Length);
  238. index += bytes.Length;
  239. }
  240. #if SERVER
  241. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  242. if (this.Network.AppType == AppType.AllServer)
  243. {
  244. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  245. Packet packet = ((TChannel)this.channel).parser.packet;
  246. packet.Flag = flag;
  247. packet.Opcode = opcode;
  248. packet.Stream.Seek(0, SeekOrigin.Begin);
  249. packet.Stream.SetLength(0);
  250. this.Network.MessagePacker.SerializeTo(message, stream);
  251. session.Run(packet);
  252. return;
  253. }
  254. #endif
  255. this.Send(stream);
  256. }
  257. public void Send(MemoryStream stream)
  258. {
  259. channel.Send(stream);
  260. }
  261. }
  262. }