Session.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. Log.Error($"message error length < 3, ip: {this.RemoteAddress}");
  59. this.network.Remove(this.Id);
  60. return;
  61. }
  62. ushort opcode = BitConverter.ToUInt16(messageBytes, 0);
  63. try
  64. {
  65. this.Run(opcode, messageBytes);
  66. }
  67. catch (Exception e)
  68. {
  69. Log.Error(e.ToString());
  70. }
  71. }
  72. }
  73. private void Run(ushort opcode, byte[] messageBytes)
  74. {
  75. int offset = 0;
  76. // opcode最高位表示是否压缩
  77. bool isCompressed = (opcode & 0x8000) > 0;
  78. if (isCompressed) // 最高位为1,表示有压缩,需要解压缩
  79. {
  80. messageBytes = ZipHelper.Decompress(messageBytes, 2, messageBytes.Length - 2);
  81. offset = 0;
  82. }
  83. else
  84. {
  85. offset = 2;
  86. }
  87. opcode &= 0x7fff;
  88. this.RunDecompressedBytes(opcode, messageBytes, offset);
  89. }
  90. private void RunDecompressedBytes(ushort opcode, byte[] messageBytes, int offset)
  91. {
  92. object message;
  93. Opcode op = (Opcode)opcode;
  94. try
  95. {
  96. Type messageType = this.network.Entity.GetComponent<OpcodeTypeComponent>().GetType(op);
  97. message = this.network.MessagePacker.DeserializeFrom(messageType, messageBytes, offset, messageBytes.Length - offset);
  98. }
  99. catch (Exception e)
  100. {
  101. Log.Error($"message deserialize error, ip: {this.RemoteAddress} {op} {e}");
  102. this.network.Remove(this.Id);
  103. return;
  104. }
  105. //Log.Debug($"recv: {MongoHelper.ToJson(message)}");
  106. AResponse response = message as AResponse;
  107. if (response != null)
  108. {
  109. // rpcFlag>0 表示这是一个rpc响应消息
  110. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  111. Action<object> action;
  112. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  113. {
  114. return;
  115. }
  116. this.requestCallback.Remove(response.RpcId);
  117. action(message);
  118. return;
  119. }
  120. this.network.MessageDispatcher.Dispatch(this, op, offset, messageBytes, (AMessage)message);
  121. }
  122. /// <summary>
  123. /// Rpc调用
  124. /// </summary>
  125. public Task<Response> Call<Response>(ARequest request, CancellationToken cancellationToken)
  126. where Response : AResponse
  127. {
  128. request.RpcId = ++RpcId;
  129. this.SendMessage(request);
  130. var tcs = new TaskCompletionSource<Response>();
  131. this.requestCallback[RpcId] = (message) =>
  132. {
  133. try
  134. {
  135. Response response = (Response)message;
  136. if (response.Error > 100)
  137. {
  138. tcs.SetException(new RpcException(response.Error, response.Message));
  139. return;
  140. }
  141. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  142. tcs.SetResult(response);
  143. }
  144. catch (Exception e)
  145. {
  146. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  147. }
  148. };
  149. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  150. return tcs.Task;
  151. }
  152. /// <summary>
  153. /// Rpc调用,发送一个消息,等待返回一个消息
  154. /// </summary>
  155. public Task<Response> Call<Response>(ARequest request) where Response : AResponse
  156. {
  157. request.RpcId = ++RpcId;
  158. this.SendMessage(request);
  159. var tcs = new TaskCompletionSource<Response>();
  160. this.requestCallback[RpcId] = (message) =>
  161. {
  162. try
  163. {
  164. Response response = (Response)message;
  165. if (response.Error > 100)
  166. {
  167. tcs.SetException(new RpcException(response.Error, response.Message));
  168. return;
  169. }
  170. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  171. tcs.SetResult(response);
  172. }
  173. catch (Exception e)
  174. {
  175. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  176. }
  177. };
  178. return tcs.Task;
  179. }
  180. public void Send(AMessage message)
  181. {
  182. if (this.Id == 0)
  183. {
  184. throw new Exception("session已经被Dispose了");
  185. }
  186. this.SendMessage(message);
  187. }
  188. public void Reply<Response>(Response message) where Response : AResponse
  189. {
  190. if (this.Id == 0)
  191. {
  192. throw new Exception("session已经被Dispose了");
  193. }
  194. this.SendMessage(message);
  195. }
  196. private void SendMessage(object message)
  197. {
  198. //Log.Debug($"send: {MongoHelper.ToJson(message)}");
  199. Opcode opcode = this.network.Entity.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  200. ushort op = (ushort)opcode;
  201. byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
  202. if (messageBytes.Length > 100)
  203. {
  204. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  205. if (newMessageBytes.Length < messageBytes.Length)
  206. {
  207. messageBytes = newMessageBytes;
  208. op |= 0x8000;
  209. }
  210. }
  211. byte[] opcodeBytes = BitConverter.GetBytes(op);
  212. this.byteses[0] = opcodeBytes;
  213. this.byteses[1] = messageBytes;
  214. channel.Send(this.byteses);
  215. }
  216. public override void Dispose()
  217. {
  218. if (this.Id == 0)
  219. {
  220. return;
  221. }
  222. long id = this.Id;
  223. base.Dispose();
  224. this.channel.Dispose();
  225. this.network.Remove(id);
  226. }
  227. }
  228. }