Session.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace Model
  6. {
  7. public sealed class Session : Entity
  8. {
  9. private static uint RpcId { get; set; }
  10. private readonly NetworkComponent network;
  11. private readonly Dictionary<uint, Action<object>> requestCallback = new Dictionary<uint, Action<object>>();
  12. private readonly AChannel channel;
  13. private bool isRpc;
  14. private readonly IMessagePacker messagePacker;
  15. public Session(NetworkComponent network, AChannel channel, IMessagePacker messagePacker)
  16. {
  17. this.network = network;
  18. this.channel = channel;
  19. this.messagePacker = messagePacker;
  20. this.StartRecv();
  21. }
  22. public string RemoteAddress
  23. {
  24. get
  25. {
  26. return this.channel.RemoteAddress;
  27. }
  28. }
  29. public ChannelType ChannelType
  30. {
  31. get
  32. {
  33. return this.channel.ChannelType;
  34. }
  35. }
  36. private async void StartRecv()
  37. {
  38. TimerComponent timerComponent = Game.Scene.GetComponent<TimerComponent>();
  39. while (true)
  40. {
  41. if (this.Id == 0)
  42. {
  43. return;
  44. }
  45. byte[] messageBytes;
  46. try
  47. {
  48. if (this.isRpc)
  49. {
  50. this.isRpc = false;
  51. await timerComponent.WaitAsync(0);
  52. }
  53. messageBytes = await channel.Recv();
  54. }
  55. catch (Exception e)
  56. {
  57. Log.Error(e.ToString());
  58. continue;
  59. }
  60. if (messageBytes.Length < 3)
  61. {
  62. continue;
  63. }
  64. ushort opcode = BitConverter.ToUInt16(messageBytes, 0);
  65. try
  66. {
  67. this.Run(opcode, messageBytes);
  68. }
  69. catch (Exception e)
  70. {
  71. Log.Error(e.ToString());
  72. }
  73. }
  74. }
  75. private void Run(ushort opcode, byte[] messageBytes)
  76. {
  77. int offset = 0;
  78. byte flag = messageBytes[2];
  79. bool isCompressed = (flag & 0x80) > 0;
  80. const int opcodeAndFlagLength = 3;
  81. if (isCompressed) // 最高位为1,表示有压缩,需要解压缩
  82. {
  83. messageBytes = ZipHelper.Decompress(messageBytes, opcodeAndFlagLength, messageBytes.Length - opcodeAndFlagLength);
  84. offset = 0;
  85. }
  86. else
  87. {
  88. offset = opcodeAndFlagLength;
  89. }
  90. this.RunDecompressedBytes(opcode, messageBytes, offset);
  91. }
  92. private void RunDecompressedBytes(ushort opcode, byte[] messageBytes, int offset)
  93. {
  94. Type messageType = this.network.Owner.GetComponent<OpcodeTypeComponent>().GetType(opcode);
  95. object message = messagePacker.DeserializeFrom(messageType, messageBytes, offset, messageBytes.Length - offset);
  96. if (message is AActorMessage)
  97. {
  98. this.network.Owner.GetComponent<ActorMessageDispatherComponent>().Handle(this, message);
  99. return;
  100. }
  101. if (message is AMessage || message is ARequest)
  102. {
  103. this.network.Owner.GetComponent<MessageDispatherComponent>().Handle(this, message);
  104. return;
  105. }
  106. if (message is AResponse response)
  107. {
  108. // rpcFlag>0 表示这是一个rpc响应消息
  109. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  110. if (!this.requestCallback.TryGetValue(response.RpcId, out Action<object> action))
  111. {
  112. return;
  113. }
  114. this.requestCallback.Remove(response.RpcId);
  115. action(message);
  116. return;
  117. }
  118. throw new Exception($"message type error: {message.GetType().FullName}");
  119. }
  120. /// <summary>
  121. /// Rpc调用
  122. /// </summary>
  123. public Task<Response> Call<Request, Response>(Request request, CancellationToken cancellationToken) where Request : ARequest
  124. where Response : AResponse
  125. {
  126. request.RpcId = ++RpcId;
  127. this.SendMessage(request);
  128. var tcs = new TaskCompletionSource<Response>();
  129. this.requestCallback[RpcId] = (message) =>
  130. {
  131. try
  132. {
  133. Response response = (Response)message;
  134. if (response.Error != 0)
  135. {
  136. tcs.SetException(new RpcException(response.Error, response.Message));
  137. return;
  138. }
  139. //Log.Debug($"recv: {response.ToJson()}");
  140. this.isRpc = true;
  141. tcs.SetResult(response);
  142. }
  143. catch (Exception e)
  144. {
  145. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  146. }
  147. };
  148. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  149. return tcs.Task;
  150. }
  151. /// <summary>
  152. /// Rpc调用,发送一个消息,等待返回一个消息
  153. /// </summary>
  154. public Task<Response> Call<Request, Response>(Request request) where Request : ARequest where Response : AResponse
  155. {
  156. request.RpcId = ++RpcId;
  157. this.SendMessage(request);
  158. var tcs = new TaskCompletionSource<Response>();
  159. this.requestCallback[RpcId] = (message) =>
  160. {
  161. try
  162. {
  163. Response response = (Response)message;
  164. if (response.Error != 0)
  165. {
  166. tcs.SetException(new RpcException(response.Error, response.Message));
  167. return;
  168. }
  169. //Log.Debug($"recv: {response.ToJson()}");
  170. this.isRpc = true;
  171. tcs.SetResult(response);
  172. }
  173. catch (Exception e)
  174. {
  175. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  176. }
  177. };
  178. return tcs.Task;
  179. }
  180. public void Send<Message>(Message message) where Message : AMessage
  181. {
  182. if (this.Id == 0)
  183. {
  184. throw new Exception("session已经被Dispose了");
  185. }
  186. this.SendMessage(message);
  187. }
  188. public void Reply<Response>(Response message) where Response : AResponse
  189. {
  190. if (this.Id == 0)
  191. {
  192. throw new Exception("session已经被Dispose了");
  193. }
  194. this.SendMessage(message);
  195. }
  196. private void SendMessage(object message)
  197. {
  198. //Log.Debug($"send: {message.ToJson()}");
  199. ushort opcode = this.network.Owner.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  200. byte[] opcodeBytes = BitConverter.GetBytes(opcode);
  201. byte[] messageBytes = messagePacker.SerializeToByteArray(message);
  202. byte flag = 0;
  203. if (messageBytes.Length > 100)
  204. {
  205. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  206. if (newMessageBytes.Length < messageBytes.Length)
  207. {
  208. messageBytes = newMessageBytes;
  209. flag |= 0x80;
  210. }
  211. }
  212. byte[] flagBytes = { flag };
  213. channel.Send(new List<byte[]> { opcodeBytes, flagBytes, messageBytes });
  214. }
  215. public override void Dispose()
  216. {
  217. if (this.Id == 0)
  218. {
  219. return;
  220. }
  221. long id = this.Id;
  222. base.Dispose();
  223. this.channel.Dispose();
  224. this.network.Remove(id);
  225. }
  226. }
  227. }