Session.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. using System.Net;
  2. using Cysharp.Threading.Tasks;
  3. using MongoDB.Bson;
  4. namespace KYFramework.Network
  5. {
  6. [ObjectSystem]
  7. public class SessionAwakeSystem : AwakeSystem<Session, AChannel>
  8. {
  9. public override void Awake(Session self, AChannel b)
  10. {
  11. self.Awake(b);
  12. }
  13. }
  14. public sealed class Session : Entity
  15. {
  16. private static int RpcId { get; set; }
  17. private AChannel channel;
  18. private readonly Dictionary<int, Action<IResponse>> requestCallback = new Dictionary<int, Action<IResponse>>();
  19. private readonly byte[] opcodeBytes = new byte[2];
  20. public Action<string> OnError;
  21. public Action<string> OnClose;
  22. public NetworkComponent Network
  23. {
  24. get
  25. {
  26. return this.GetParent<NetworkComponent>();
  27. }
  28. }
  29. public int Error
  30. {
  31. get
  32. {
  33. return this.channel.Error;
  34. }
  35. set
  36. {
  37. this.channel.Error = value;
  38. }
  39. }
  40. public void Awake(AChannel aChannel)
  41. {
  42. this.channel = aChannel;
  43. this.requestCallback.Clear();
  44. long id = this.Id;
  45. channel.ErrorCallback += (c, e) =>
  46. {
  47. OnClose?.Invoke(c.RemoteAddress.ToString());
  48. this.Network.Remove(id);
  49. };
  50. channel.ReadCallback += this.OnRead;
  51. }
  52. public override void Dispose()
  53. {
  54. if (this.IsDisposed)
  55. {
  56. return;
  57. }
  58. this.Network.Remove(this.Id);
  59. base.Dispose();
  60. foreach (Action<IResponse> action in this.requestCallback.Values.ToArray())
  61. {
  62. action.Invoke(new ResponseMessage { Error = this.Error });
  63. }
  64. this.channel.Dispose();
  65. this.requestCallback.Clear();
  66. }
  67. public void Start()
  68. {
  69. this.channel.Start();
  70. }
  71. public IPEndPoint RemoteAddress
  72. {
  73. get
  74. {
  75. return this.channel.RemoteAddress;
  76. }
  77. }
  78. public ChannelType ChannelType
  79. {
  80. get
  81. {
  82. return this.channel.ChannelType;
  83. }
  84. }
  85. public MemoryStream Stream
  86. {
  87. get
  88. {
  89. return this.channel.Stream;
  90. }
  91. }
  92. public void OnRead(MemoryStream memoryStream)
  93. {
  94. try
  95. {
  96. this.Run(memoryStream);
  97. }
  98. catch (Exception e)
  99. {
  100. Log.Error(e);
  101. }
  102. }
  103. private void Run(MemoryStream memoryStream)
  104. {
  105. memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  106. ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);
  107. object message;
  108. try
  109. {
  110. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  111. object instance = opcodeTypeComponent.GetInstance(opcode);
  112. message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);
  113. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  114. {
  115. Log.Info("receive -->" + message.ToJson());
  116. }
  117. }
  118. catch (Exception e)
  119. {
  120. // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
  121. Log.Error($"opcode: {opcode} {this.Network.Count} {e} ");
  122. this.Error = ErrorCode.ERR_PacketParserError;
  123. this.Network.Remove(this.Id);
  124. return;
  125. }
  126. IResponse response = message as IResponse;
  127. if (response == null)
  128. {
  129. this.Network.MessageDispatcher.Dispatch(this, opcode, message);
  130. return;
  131. }
  132. Action<IResponse> action;
  133. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  134. {
  135. throw new Exception($"not found rpc, response message: {StringHelper.MessageToStr(response)}");
  136. }
  137. this.requestCallback.Remove(response.RpcId);
  138. action(response);
  139. }
  140. public UniTask<IResponse> Call(IRequest request)
  141. {
  142. int rpcId = ++RpcId;
  143. var tcs = new UniTaskCompletionSource<IResponse>();
  144. this.requestCallback[rpcId] = (response) =>
  145. {
  146. try
  147. {
  148. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  149. {
  150. //TODO Show MessageBox
  151. //MessageBoxHelper.Show("网络异常!请检查..." , "连接失败").BtnYes = () =>
  152. //{
  153. //LoginHelper.Reset();
  154. //};
  155. OnError?.Invoke("网络异常!请检查...");
  156. }
  157. tcs.TrySetResult(response);
  158. }
  159. catch (Exception e)
  160. {
  161. tcs.TrySetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  162. }
  163. };
  164. request.RpcId = rpcId;
  165. this.Send(request);
  166. return tcs.Task;
  167. }
  168. public UniTask<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  169. {
  170. int rpcId = ++RpcId;
  171. var tcs = new UniTaskCompletionSource<IResponse>();
  172. this.requestCallback[rpcId] = (response) =>
  173. {
  174. try
  175. {
  176. if (ErrorCode.IsRpcNeedThrowException(response.Error))
  177. {
  178. OnError?.Invoke("网络异常!请检查...");
  179. return;
  180. }
  181. tcs.TrySetResult(response);
  182. }
  183. catch (Exception e)
  184. {
  185. tcs.TrySetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  186. }
  187. };
  188. cancellationToken.Register(() => this.requestCallback.Remove(rpcId));
  189. request.RpcId = rpcId;
  190. this.Send(request);
  191. return tcs.Task;
  192. }
  193. public void Reply(IResponse message)
  194. {
  195. if (this.IsDisposed)
  196. {
  197. throw new Exception("session已经被Dispose了");
  198. }
  199. this.Send(message);
  200. }
  201. public void Send(IMessage message)
  202. {
  203. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  204. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  205. Send(opcode, message);
  206. }
  207. public void Send(ushort opcode, object message)
  208. {
  209. if (this.IsDisposed)
  210. {
  211. throw new Exception("session已经被Dispose了");
  212. }
  213. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  214. {
  215. Log.Info("send --> " + message.ToJson());
  216. }
  217. MemoryStream stream = this.Stream;
  218. stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
  219. stream.SetLength(Packet.MessageIndex);
  220. this.Network.MessagePacker.SerializeTo(message, stream);
  221. stream.Seek(0, SeekOrigin.Begin);
  222. opcodeBytes.WriteTo(0, opcode);
  223. Array.Copy(opcodeBytes, 0, stream.GetBuffer(), 0, opcodeBytes.Length);
  224. this.Send(stream);
  225. }
  226. public void Send(MemoryStream stream)
  227. {
  228. channel.Send(stream);
  229. }
  230. }
  231. }