Session.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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.Owner.GetComponent<OpcodeTypeComponent>().GetType(opcode);
  91. object message = this.network.MessagePacker.DeserializeFrom(messageType, messageBytes, offset, messageBytes.Length - offset);
  92. AResponse response = message as AResponse;
  93. if (response != null)
  94. {
  95. // rpcFlag>0 表示这是一个rpc响应消息
  96. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  97. Action<object> action;
  98. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  99. {
  100. return;
  101. }
  102. this.requestCallback.Remove(response.RpcId);
  103. action(message);
  104. return;
  105. }
  106. this.network.MessageDispatcher.Dispatch(this, opcode, offset, messageBytes, message);
  107. }
  108. /// <summary>
  109. /// Rpc调用
  110. /// </summary>
  111. public Task<Response> Call<Request, Response>(Request request, CancellationToken cancellationToken) where Request : ARequest
  112. where Response : AResponse
  113. {
  114. request.RpcId = ++RpcId;
  115. this.SendMessage(request);
  116. var tcs = new TaskCompletionSource<Response>();
  117. this.requestCallback[RpcId] = (message) =>
  118. {
  119. try
  120. {
  121. Response response = (Response)message;
  122. if (response.Error > 100)
  123. {
  124. tcs.SetException(new RpcException(response.Error, response.Message));
  125. return;
  126. }
  127. //Log.Debug($"recv: {response.ToJson()}");
  128. tcs.SetResult(response);
  129. }
  130. catch (Exception e)
  131. {
  132. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  133. }
  134. };
  135. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  136. return tcs.Task;
  137. }
  138. /// <summary>
  139. /// Rpc调用,发送一个消息,等待返回一个消息
  140. /// </summary>
  141. public Task<Response> Call<Request, Response>(Request request) where Request : ARequest where Response : AResponse
  142. {
  143. request.RpcId = ++RpcId;
  144. this.SendMessage(request);
  145. var tcs = new TaskCompletionSource<Response>();
  146. this.requestCallback[RpcId] = (message) =>
  147. {
  148. try
  149. {
  150. Response response = (Response)message;
  151. if (response.Error > 100)
  152. {
  153. tcs.SetException(new RpcException(response.Error, response.Message));
  154. return;
  155. }
  156. //Log.Debug($"recv: {response.ToJson()}");
  157. tcs.SetResult(response);
  158. }
  159. catch (Exception e)
  160. {
  161. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  162. }
  163. };
  164. return tcs.Task;
  165. }
  166. public void Send<Message>(Message message) where Message : AMessage
  167. {
  168. if (this.Id == 0)
  169. {
  170. throw new Exception("session已经被Dispose了");
  171. }
  172. this.SendMessage(message);
  173. }
  174. public void Reply<Response>(Response message) where Response : AResponse
  175. {
  176. if (this.Id == 0)
  177. {
  178. throw new Exception("session已经被Dispose了");
  179. }
  180. this.SendMessage(message);
  181. }
  182. private void SendMessage(object message)
  183. {
  184. //Log.Debug($"send: {message.ToJson()}");
  185. ushort opcode = this.network.Owner.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  186. opcode = NetworkHelper.HostToNetworkOrder(opcode);
  187. byte[] opcodeBytes = BitConverter.GetBytes(opcode);
  188. byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
  189. byte flag = 0;
  190. if (messageBytes.Length > 100)
  191. {
  192. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  193. if (newMessageBytes.Length < messageBytes.Length)
  194. {
  195. messageBytes = newMessageBytes;
  196. flag |= 0x80;
  197. }
  198. }
  199. byte[] flagBytes = { flag };
  200. channel.Send(new List<byte[]> { opcodeBytes, flagBytes, messageBytes });
  201. }
  202. public override void Dispose()
  203. {
  204. if (this.Id == 0)
  205. {
  206. return;
  207. }
  208. long id = this.Id;
  209. base.Dispose();
  210. this.channel.Dispose();
  211. this.network.Remove(id);
  212. }
  213. }
  214. }