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 MongoDB.Bson;
  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. private bool isRpc;
  15. public Session(NetworkComponent network, AChannel channel)
  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. TimerComponent timerComponent = Game.Scene.GetComponent<TimerComponent>();
  38. while (true)
  39. {
  40. if (this.Id == 0)
  41. {
  42. return;
  43. }
  44. byte[] messageBytes;
  45. try
  46. {
  47. if (this.isRpc)
  48. {
  49. this.isRpc = false;
  50. await timerComponent.WaitAsync(0);
  51. }
  52. messageBytes = await channel.Recv();
  53. }
  54. catch (Exception e)
  55. {
  56. Log.Error(e.ToString());
  57. continue;
  58. }
  59. if (messageBytes.Length < 6)
  60. {
  61. continue;
  62. }
  63. ushort opcode = BitConverter.ToUInt16(messageBytes, 0);
  64. try
  65. {
  66. this.Run(opcode, messageBytes);
  67. }
  68. catch (Exception e)
  69. {
  70. Log.Error(e.ToString());
  71. }
  72. }
  73. }
  74. private void Run(ushort opcode, byte[] messageBytes)
  75. {
  76. int offset = 0;
  77. uint flag = BitConverter.ToUInt32(messageBytes, 2);
  78. uint rpcFlag = flag & 0x40000000;
  79. uint rpcId = flag & 0x3fffffff;
  80. bool isCompressed = (flag & 0x80000000) > 0;
  81. if (isCompressed) // 最高位为1,表示有压缩,需要解压缩
  82. {
  83. messageBytes = ZipHelper.Decompress(messageBytes, 6, messageBytes.Length - 6);
  84. offset = 0;
  85. }
  86. else
  87. {
  88. offset = 6;
  89. }
  90. this.RunDecompressedBytes(opcode, rpcId, rpcFlag, messageBytes, offset);
  91. }
  92. private void RunDecompressedBytes(ushort opcode, uint rpcId, uint rpcFlag, byte[] messageBytes, int offset)
  93. {
  94. // 普通消息或者是Rpc请求消息
  95. if (rpcFlag == 0)
  96. {
  97. MessageInfo messageInfo = new MessageInfo(opcode, messageBytes, offset, rpcId);
  98. this.network.Owner.GetComponent<MessageDispatherComponent>().Handle(this, messageInfo);
  99. return;
  100. }
  101. // rpcFlag>0 表示这是一个rpc响应消息
  102. Action<byte[], int, int> action;
  103. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  104. if (!this.requestCallback.TryGetValue(rpcId, out 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. }