Session.cs 5.5 KB

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