Session.cs 6.7 KB

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