Session.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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;
  94. try
  95. {
  96. op = (Opcode)opcode;
  97. Type messageType = this.network.Entity.GetComponent<OpcodeTypeComponent>().GetType(op);
  98. message = this.network.MessagePacker.DeserializeFrom(messageType, messageBytes, offset, messageBytes.Length - offset);
  99. }
  100. catch (Exception e)
  101. {
  102. Log.Error($"message deserialize error, ip: {this.RemoteAddress} {opcode} {e}");
  103. this.network.Remove(this.Id);
  104. return;
  105. }
  106. //Log.Debug($"recv: {MongoHelper.ToJson(message)}");
  107. AResponse response = message as AResponse;
  108. if (response != null)
  109. {
  110. // rpcFlag>0 表示这是一个rpc响应消息
  111. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  112. Action<object> action;
  113. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  114. {
  115. return;
  116. }
  117. this.requestCallback.Remove(response.RpcId);
  118. action(message);
  119. return;
  120. }
  121. this.network.MessageDispatcher.Dispatch(this, op, offset, messageBytes, (AMessage)message);
  122. }
  123. /// <summary>
  124. /// Rpc调用,发送一个消息,等待返回一个消息
  125. /// </summary>
  126. public Task<AResponse> Call(ARequest request)
  127. {
  128. request.RpcId = ++RpcId;
  129. this.SendMessage(request);
  130. var tcs = new TaskCompletionSource<AResponse>();
  131. this.requestCallback[RpcId] = (message) =>
  132. {
  133. try
  134. {
  135. AResponse response = (AResponse)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: {message.GetType().FullName}", e));
  147. }
  148. };
  149. return tcs.Task;
  150. }
  151. /// <summary>
  152. /// Rpc调用
  153. /// </summary>
  154. public Task<AResponse> Call(ARequest request, CancellationToken cancellationToken)
  155. {
  156. request.RpcId = ++RpcId;
  157. this.SendMessage(request);
  158. var tcs = new TaskCompletionSource<AResponse>();
  159. this.requestCallback[RpcId] = (message) =>
  160. {
  161. try
  162. {
  163. AResponse response = (AResponse)message;
  164. if (response.Error > 100)
  165. {
  166. tcs.SetException(new RpcException(response.Error, response.Message));
  167. return;
  168. }
  169. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  170. tcs.SetResult(response);
  171. }
  172. catch (Exception e)
  173. {
  174. tcs.SetException(new Exception($"Rpc Error: {request.GetType().FullName}", e));
  175. }
  176. };
  177. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  178. return tcs.Task;
  179. }
  180. /// <summary>
  181. /// Rpc调用
  182. /// </summary>
  183. public Task<Response> Call<Response>(ARequest request, CancellationToken cancellationToken)
  184. where Response : AResponse
  185. {
  186. request.RpcId = ++RpcId;
  187. this.SendMessage(request);
  188. var tcs = new TaskCompletionSource<Response>();
  189. this.requestCallback[RpcId] = (message) =>
  190. {
  191. try
  192. {
  193. Response response = (Response)message;
  194. if (response.Error > 100)
  195. {
  196. tcs.SetException(new RpcException(response.Error, response.Message));
  197. return;
  198. }
  199. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  200. tcs.SetResult(response);
  201. }
  202. catch (Exception e)
  203. {
  204. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  205. }
  206. };
  207. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  208. return tcs.Task;
  209. }
  210. /// <summary>
  211. /// Rpc调用,发送一个消息,等待返回一个消息
  212. /// </summary>
  213. public Task<Response> Call<Response>(ARequest request) where Response : AResponse
  214. {
  215. request.RpcId = ++RpcId;
  216. this.SendMessage(request);
  217. var tcs = new TaskCompletionSource<Response>();
  218. this.requestCallback[RpcId] = (message) =>
  219. {
  220. try
  221. {
  222. Response response = (Response)message;
  223. if (response.Error > 100)
  224. {
  225. tcs.SetException(new RpcException(response.Error, response.Message));
  226. return;
  227. }
  228. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  229. tcs.SetResult(response);
  230. }
  231. catch (Exception e)
  232. {
  233. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  234. }
  235. };
  236. return tcs.Task;
  237. }
  238. public void Send(AMessage message)
  239. {
  240. if (this.Id == 0)
  241. {
  242. throw new Exception("session已经被Dispose了");
  243. }
  244. this.SendMessage(message);
  245. }
  246. public void Reply<Response>(Response message) where Response : AResponse
  247. {
  248. if (this.Id == 0)
  249. {
  250. throw new Exception("session已经被Dispose了");
  251. }
  252. this.SendMessage(message);
  253. }
  254. private void SendMessage(object message)
  255. {
  256. //Log.Debug($"send: {MongoHelper.ToJson(message)}");
  257. Opcode opcode = this.network.Entity.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  258. ushort op = (ushort)opcode;
  259. byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
  260. if (messageBytes.Length > 100)
  261. {
  262. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  263. if (newMessageBytes.Length < messageBytes.Length)
  264. {
  265. messageBytes = newMessageBytes;
  266. op |= 0x8000;
  267. }
  268. }
  269. byte[] opcodeBytes = BitConverter.GetBytes(op);
  270. this.byteses[0] = opcodeBytes;
  271. this.byteses[1] = messageBytes;
  272. channel.Send(this.byteses);
  273. }
  274. public override void Dispose()
  275. {
  276. if (this.Id == 0)
  277. {
  278. return;
  279. }
  280. long id = this.Id;
  281. base.Dispose();
  282. this.channel.Dispose();
  283. this.network.Remove(id);
  284. }
  285. }
  286. }