Session.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using LitJson;
  6. using Model;
  7. using MongoDB.Bson;
  8. namespace Hotfix
  9. {
  10. public sealed class Session : HotfixEntity
  11. {
  12. private static uint RpcId { get; set; }
  13. private readonly NetworkComponent network;
  14. private readonly Dictionary<uint, Action<byte[], int, int>> requestCallback = new Dictionary<uint, Action<byte[], int, int>>();
  15. private readonly AChannel channel;
  16. private bool isRpc;
  17. public Session(NetworkComponent network, AChannel channel)
  18. {
  19. this.network = network;
  20. this.channel = channel;
  21. this.StartRecv();
  22. }
  23. public string RemoteAddress
  24. {
  25. get
  26. {
  27. return this.channel.RemoteAddress;
  28. }
  29. }
  30. public ChannelType ChannelType
  31. {
  32. get
  33. {
  34. return this.channel.ChannelType;
  35. }
  36. }
  37. private async void StartRecv()
  38. {
  39. TimerComponent timerComponent = Hotfix.Scene.GetComponent<TimerComponent>();
  40. while (true)
  41. {
  42. if (this.Id == 0)
  43. {
  44. return;
  45. }
  46. byte[] messageBytes;
  47. try
  48. {
  49. if (this.isRpc)
  50. {
  51. this.isRpc = false;
  52. await timerComponent.WaitAsync(0);
  53. }
  54. messageBytes = await channel.Recv();
  55. }
  56. catch (Exception e)
  57. {
  58. Log.Error(e.ToString());
  59. continue;
  60. }
  61. if (messageBytes.Length < 6)
  62. {
  63. continue;
  64. }
  65. ushort opcode = BitConverter.ToUInt16(messageBytes, 0);
  66. try
  67. {
  68. this.Run(opcode, messageBytes);
  69. }
  70. catch (Exception e)
  71. {
  72. Log.Error(e.ToString());
  73. }
  74. }
  75. }
  76. private void Run(ushort opcode, byte[] messageBytes)
  77. {
  78. int offset = 0;
  79. uint flag = BitConverter.ToUInt32(messageBytes, 2);
  80. uint rpcFlag = flag & 0x40000000;
  81. uint rpcId = flag & 0x3fffffff;
  82. bool isCompressed = (flag & 0x80000000) > 0;
  83. if (isCompressed) // 最高位为1,表示有压缩,需要解压缩
  84. {
  85. messageBytes = ZipHelper.Decompress(messageBytes, 6, messageBytes.Length - 6);
  86. offset = 0;
  87. }
  88. else
  89. {
  90. offset = 6;
  91. }
  92. this.RunDecompressedBytes(opcode, rpcId, rpcFlag, messageBytes, offset);
  93. }
  94. private void RunDecompressedBytes(ushort opcode, uint rpcId, uint rpcFlag, byte[] messageBytes, int offset)
  95. {
  96. // 普通消息或者是Rpc请求消息
  97. if (rpcFlag == 0)
  98. {
  99. MessageInfo messageInfo = new MessageInfo(opcode, messageBytes, offset, rpcId);
  100. this.network.Owner.GetComponent<MessageDispatherComponent>().Handle(this, 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. //Log.Debug($"send: {message.ToJson()}");
  190. ushort opcode = this.network.Owner.GetComponent<MessageDispatherComponent>().GetOpcode(message.GetType());
  191. byte[] opcodeBytes = BitConverter.GetBytes(opcode);
  192. if (!isCall)
  193. {
  194. rpcId = rpcId | 0x40000000;
  195. }
  196. byte[] messageBytes = JsonHelper.ToJson(message).ToByteArray();
  197. if (messageBytes.Length > 100)
  198. {
  199. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  200. if (newMessageBytes.Length < messageBytes.Length)
  201. {
  202. messageBytes = newMessageBytes;
  203. rpcId = rpcId | 0x80000000;
  204. }
  205. }
  206. byte[] seqBytes = BitConverter.GetBytes(rpcId);
  207. channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
  208. }
  209. public override void Dispose()
  210. {
  211. if (this.Id == 0)
  212. {
  213. return;
  214. }
  215. long id = this.Id;
  216. base.Dispose();
  217. this.channel.Dispose();
  218. this.network.Remove(id);
  219. }
  220. }
  221. }