Session.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. bool isCompressed = (flag & 0x80000000) > 0;
  80. if (isCompressed) // 最高位为1,表示有压缩,需要解压缩
  81. {
  82. messageBytes = ZipHelper.Decompress(messageBytes, 6, messageBytes.Length - 6);
  83. offset = 0;
  84. }
  85. else
  86. {
  87. offset = 6;
  88. }
  89. this.RunDecompressedBytes(opcode, flag, messageBytes, offset);
  90. }
  91. private void RunDecompressedBytes(ushort opcode, uint flag, byte[] messageBytes, int offset)
  92. {
  93. uint rpcFlag = flag & 0x40000000;
  94. uint rpcId = flag & 0x3fffffff;
  95. // 普通消息或者是Rpc请求消息
  96. if (rpcFlag == 0)
  97. {
  98. MessageInfo messageInfo = new MessageInfo(opcode, messageBytes, offset, rpcId);
  99. Type messageType = this.network.Owner.GetComponent<OpcodeTypeComponent>().GetType(messageInfo.Opcode);
  100. object message = MongoHelper.FromBson(messageType, messageInfo.MessageBytes, messageInfo.Offset, messageInfo.Count);
  101. messageInfo.Message = message;
  102. if (message is AActorMessage)
  103. {
  104. this.network.Owner.GetComponent<ActorMessageDispatherComponent>().Handle(this, messageInfo);
  105. }
  106. else
  107. {
  108. this.network.Owner.GetComponent<MessageDispatherComponent>().Handle(this, messageInfo);
  109. }
  110. return;
  111. }
  112. // rpcFlag>0 表示这是一个rpc响应消息
  113. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  114. if (!this.requestCallback.TryGetValue(rpcId, out Action<byte[], int, int> action))
  115. {
  116. return;
  117. }
  118. this.requestCallback.Remove(rpcId);
  119. action(messageBytes, offset, messageBytes.Length - offset);
  120. }
  121. /// <summary>
  122. /// Rpc调用
  123. /// </summary>
  124. public Task<Response> Call<Request, Response>(Request request, CancellationToken cancellationToken) where Request : ARequest
  125. where Response : AResponse
  126. {
  127. this.SendMessage(++RpcId, request);
  128. var tcs = new TaskCompletionSource<Response>();
  129. this.requestCallback[RpcId] = (bytes, offset, count) =>
  130. {
  131. try
  132. {
  133. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  134. if (response.Error != 0)
  135. {
  136. tcs.SetException(new RpcException(response.Error, response.Message));
  137. return;
  138. }
  139. //Log.Debug($"recv: {response.ToJson()}");
  140. this.isRpc = true;
  141. tcs.SetResult(response);
  142. }
  143. catch (Exception e)
  144. {
  145. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  146. }
  147. };
  148. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  149. return tcs.Task;
  150. }
  151. /// <summary>
  152. /// Rpc调用,发送一个消息,等待返回一个消息
  153. /// </summary>
  154. public Task<Response> Call<Request, Response>(Request request) where Request : ARequest where Response : AResponse
  155. {
  156. this.SendMessage(++RpcId, request);
  157. var tcs = new TaskCompletionSource<Response>();
  158. this.requestCallback[RpcId] = (bytes, offset, count) =>
  159. {
  160. try
  161. {
  162. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  163. if (response.Error != 0)
  164. {
  165. tcs.SetException(new RpcException(response.Error, response.Message));
  166. return;
  167. }
  168. //Log.Info($"recv: {response.ToJson()}");
  169. this.isRpc = true;
  170. tcs.SetResult(response);
  171. }
  172. catch (Exception e)
  173. {
  174. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  175. }
  176. };
  177. return tcs.Task;
  178. }
  179. public void Send<Message>(Message message) where Message : AMessage
  180. {
  181. if (this.Id == 0)
  182. {
  183. throw new Exception("session已经被Dispose了");
  184. }
  185. this.SendMessage(0, message);
  186. }
  187. public void Reply<Response>(uint rpcId, Response message)
  188. {
  189. if (this.Id == 0)
  190. {
  191. throw new Exception("session已经被Dispose了");
  192. }
  193. this.SendMessage(rpcId, message, false);
  194. }
  195. private void SendMessage(uint rpcId, object message, bool isCall = true)
  196. {
  197. //Log.Debug($"send: {message.ToJson()}");
  198. ushort opcode = this.network.Owner.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  199. byte[] opcodeBytes = BitConverter.GetBytes(opcode);
  200. if (!isCall)
  201. {
  202. rpcId = rpcId | 0x40000000;
  203. }
  204. byte[] messageBytes = message.ToBson();
  205. if (messageBytes.Length > 100)
  206. {
  207. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  208. if (newMessageBytes.Length < messageBytes.Length)
  209. {
  210. messageBytes = newMessageBytes;
  211. rpcId = rpcId | 0x80000000;
  212. }
  213. }
  214. byte[] seqBytes = BitConverter.GetBytes(rpcId);
  215. channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
  216. }
  217. public override void Dispose()
  218. {
  219. if (this.Id == 0)
  220. {
  221. return;
  222. }
  223. long id = this.Id;
  224. base.Dispose();
  225. this.channel.Dispose();
  226. this.network.Remove(id);
  227. }
  228. }
  229. }