Session.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Model;
  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. Action<byte[], int, int> action;
  104. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  105. if (!this.requestCallback.TryGetValue(rpcId, out action))
  106. {
  107. return;
  108. }
  109. this.requestCallback.Remove(rpcId);
  110. action(messageBytes, offset, messageBytes.Length - offset);
  111. }
  112. /// <summary>
  113. /// Rpc调用
  114. /// </summary>
  115. public Task<Response> Call<Request, Response>(Request request, CancellationToken cancellationToken) where Request : ARequest
  116. where Response : AResponse
  117. {
  118. this.SendMessage(++RpcId, request);
  119. var tcs = new TaskCompletionSource<Response>();
  120. this.requestCallback[RpcId] = (bytes, offset, count) =>
  121. {
  122. try
  123. {
  124. Response response = JsonHelper.FromJson<Response>(bytes, offset, count);
  125. if (response.Error != 0)
  126. {
  127. tcs.SetException(new RpcException(response.Error, response.Message));
  128. return;
  129. }
  130. //Log.Debug($"recv: {response.ToJson()}");
  131. this.isRpc = true;
  132. tcs.SetResult(response);
  133. }
  134. catch (Exception e)
  135. {
  136. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  137. }
  138. };
  139. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  140. return tcs.Task;
  141. }
  142. /// <summary>
  143. /// Rpc调用,发送一个消息,等待返回一个消息
  144. /// </summary>
  145. public Task<Response> Call<Request, Response>(Request request) where Request : ARequest where Response : AResponse
  146. {
  147. this.SendMessage(++RpcId, request);
  148. var tcs = new TaskCompletionSource<Response>();
  149. this.requestCallback[RpcId] = (bytes, offset, count) =>
  150. {
  151. try
  152. {
  153. Response response = JsonHelper.FromJson<Response>(bytes, offset, count);
  154. if (response.Error != 0)
  155. {
  156. tcs.SetException(new RpcException(response.Error, response.Message));
  157. return;
  158. }
  159. //Log.Info($"recv: {response.ToJson()}");
  160. this.isRpc = true;
  161. tcs.SetResult(response);
  162. }
  163. catch (Exception e)
  164. {
  165. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  166. }
  167. };
  168. return tcs.Task;
  169. }
  170. public void Send<Message>(Message message) where Message : AMessage
  171. {
  172. if (this.Id == 0)
  173. {
  174. throw new Exception("session已经被Dispose了");
  175. }
  176. this.SendMessage(0, message);
  177. }
  178. public void Reply<Response>(uint rpcId, Response message) where Response : AResponse
  179. {
  180. if (this.Id == 0)
  181. {
  182. throw new Exception("session已经被Dispose了");
  183. }
  184. this.SendMessage(rpcId, message, false);
  185. }
  186. private void SendMessage(uint rpcId, object message, bool isCall = true)
  187. {
  188. //Log.Debug($"send: {message.ToJson()}");
  189. ushort opcode = this.network.Owner.GetComponent<MessageDispatherComponent>().GetOpcode(message.GetType());
  190. byte[] opcodeBytes = BitConverter.GetBytes(opcode);
  191. if (!isCall)
  192. {
  193. rpcId = rpcId | 0x40000000;
  194. }
  195. byte[] messageBytes = JsonHelper.ToJson(message).ToByteArray();
  196. if (messageBytes.Length > 100)
  197. {
  198. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  199. if (newMessageBytes.Length < messageBytes.Length)
  200. {
  201. messageBytes = newMessageBytes;
  202. rpcId = rpcId | 0x80000000;
  203. }
  204. }
  205. byte[] seqBytes = BitConverter.GetBytes(rpcId);
  206. channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
  207. }
  208. public override void Dispose()
  209. {
  210. if (this.Id == 0)
  211. {
  212. return;
  213. }
  214. long id = this.Id;
  215. base.Dispose();
  216. this.channel.Dispose();
  217. this.network.Remove(id);
  218. }
  219. }
  220. }