Session.cs 5.8 KB

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