Session.cs 5.6 KB

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