Session.cs 6.0 KB

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