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