Session.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. // 普通消息或者是Rpc请求消息
  81. if (rpcFlag == 0)
  82. {
  83. MessageInfo messageInfo = new MessageInfo(opcode, messageBytes, offset, rpcId);
  84. this.scene.GetComponent<MessageDispatherComponent>().Handle(this, messageInfo);
  85. return;
  86. }
  87. // rpcFlag>0 表示这是一个rpc响应消息
  88. Action<byte[], int, int> action;
  89. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  90. if (!this.requestCallback.TryGetValue(rpcId, out action))
  91. {
  92. return;
  93. }
  94. this.requestCallback.Remove(rpcId);
  95. action(messageBytes, offset, messageBytes.Length - offset);
  96. }
  97. /// <summary>
  98. /// Rpc调用
  99. /// </summary>
  100. public Task<Response> Call<Request, Response>(Request request, CancellationToken cancellationToken)
  101. where Request : ARequest
  102. where Response : AResponse
  103. {
  104. this.SendMessage(++RpcId, request);
  105. var tcs = new TaskCompletionSource<Response>();
  106. this.requestCallback[RpcId] = (bytes, offset, count) =>
  107. {
  108. try
  109. {
  110. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  111. if (response.Error != 0)
  112. {
  113. tcs.SetException(new RpcException(response.Error, response.Message));
  114. return;
  115. }
  116. tcs.SetResult(response);
  117. }
  118. catch (Exception e)
  119. {
  120. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  121. }
  122. };
  123. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  124. return tcs.Task;
  125. }
  126. /// <summary>
  127. /// Rpc调用,发送一个消息,等待返回一个消息
  128. /// </summary>
  129. public Task<Response> Call<Request, Response>(Request request)
  130. where Request : ARequest
  131. where Response : AResponse
  132. {
  133. this.SendMessage(++RpcId, request);
  134. var tcs = new TaskCompletionSource<Response>();
  135. this.requestCallback[RpcId] = (bytes, offset, count) =>
  136. {
  137. try
  138. {
  139. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  140. if (response.Error != 0)
  141. {
  142. tcs.SetException(new RpcException(response.Error, response.Message));
  143. return;
  144. }
  145. tcs.SetResult(response);
  146. }
  147. catch (Exception e)
  148. {
  149. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  150. }
  151. };
  152. return tcs.Task;
  153. }
  154. public void Send<Message>(Message message) where Message : AMessage
  155. {
  156. if (this.Id == 0)
  157. {
  158. throw new Exception("session已经被Dispose了");
  159. }
  160. this.SendMessage(0, message);
  161. }
  162. public void Reply<Response>(uint rpcId, Response message) where Response : AResponse
  163. {
  164. if (this.Id == 0)
  165. {
  166. throw new Exception("session已经被Dispose了");
  167. }
  168. this.SendMessage(rpcId, message, false);
  169. }
  170. private void SendMessage(uint rpcId, object message, bool isCall = true)
  171. {
  172. ushort opcode = this.scene.GetComponent<MessageDispatherComponent>().GetOpcode(message.GetType());
  173. byte[] opcodeBytes = BitConverter.GetBytes(opcode);
  174. if (!isCall)
  175. {
  176. rpcId = rpcId | 0x40000000;
  177. }
  178. byte[] messageBytes = MongoHelper.ToBson(message);
  179. if (messageBytes.Length > 100)
  180. {
  181. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  182. if (newMessageBytes.Length < messageBytes.Length)
  183. {
  184. messageBytes = newMessageBytes;
  185. rpcId = rpcId | 0x80000000;
  186. }
  187. }
  188. byte[] seqBytes = BitConverter.GetBytes(rpcId);
  189. channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
  190. }
  191. public override void Dispose()
  192. {
  193. if (this.Id == 0)
  194. {
  195. return;
  196. }
  197. base.Dispose();
  198. this.channel.Dispose();
  199. }
  200. }
  201. }