Session.cs 6.5 KB

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