Session.cs 5.3 KB

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