Session.cs 5.4 KB

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