Session.cs 5.5 KB

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