Session.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 void CallWithAction(ARequest request, Action<AResponse> action)
  127. {
  128. request.RpcId = ++RpcId;
  129. this.SendMessage(request);
  130. this.requestCallback[RpcId] = (message) =>
  131. {
  132. try
  133. {
  134. AResponse response = (AResponse)message;
  135. action(response);
  136. }
  137. catch (Exception e)
  138. {
  139. Log.Error(e.ToString());
  140. }
  141. };
  142. }
  143. /// <summary>
  144. /// Rpc调用,发送一个消息,等待返回一个消息
  145. /// </summary>
  146. public Task<AResponse> Call(ARequest request, bool isHotfix)
  147. {
  148. request.RpcId = ++RpcId;
  149. this.SendMessage(request);
  150. var tcs = new TaskCompletionSource<AResponse>();
  151. this.requestCallback[RpcId] = (message) =>
  152. {
  153. try
  154. {
  155. AResponse response = (AResponse)message;
  156. if (response.Error > 100)
  157. {
  158. tcs.SetException(new RpcException(response.Error, response.Message));
  159. return;
  160. }
  161. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  162. tcs.SetResult(response);
  163. }
  164. catch (Exception e)
  165. {
  166. tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
  167. }
  168. };
  169. return tcs.Task;
  170. }
  171. /// <summary>
  172. /// Rpc调用
  173. /// </summary>
  174. public Task<AResponse> Call(ARequest request, bool isHotfix, CancellationToken cancellationToken)
  175. {
  176. request.RpcId = ++RpcId;
  177. this.SendMessage(request);
  178. var tcs = new TaskCompletionSource<AResponse>();
  179. this.requestCallback[RpcId] = (message) =>
  180. {
  181. try
  182. {
  183. AResponse response = (AResponse)message;
  184. if (response.Error > 100)
  185. {
  186. tcs.SetException(new RpcException(response.Error, response.Message));
  187. return;
  188. }
  189. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  190. tcs.SetResult(response);
  191. }
  192. catch (Exception e)
  193. {
  194. tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
  195. }
  196. };
  197. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  198. return tcs.Task;
  199. }
  200. /// <summary>
  201. /// Rpc调用,发送一个消息,等待返回一个消息
  202. /// </summary>
  203. public Task<Response> Call<Response>(ARequest request) where Response : AResponse
  204. {
  205. request.RpcId = ++RpcId;
  206. this.SendMessage(request);
  207. var tcs = new TaskCompletionSource<Response>();
  208. this.requestCallback[RpcId] = (message) =>
  209. {
  210. try
  211. {
  212. Response response = (Response)message;
  213. if (response.Error > 100)
  214. {
  215. tcs.SetException(new RpcException(response.Error, response.Message));
  216. return;
  217. }
  218. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  219. tcs.SetResult(response);
  220. }
  221. catch (Exception e)
  222. {
  223. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  224. }
  225. };
  226. return tcs.Task;
  227. }
  228. /// <summary>
  229. /// Rpc调用
  230. /// </summary>
  231. public Task<Response> Call<Response>(ARequest request, CancellationToken cancellationToken)
  232. where Response : AResponse
  233. {
  234. request.RpcId = ++RpcId;
  235. this.SendMessage(request);
  236. var tcs = new TaskCompletionSource<Response>();
  237. this.requestCallback[RpcId] = (message) =>
  238. {
  239. try
  240. {
  241. Response response = (Response)message;
  242. if (response.Error > 100)
  243. {
  244. tcs.SetException(new RpcException(response.Error, response.Message));
  245. return;
  246. }
  247. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  248. tcs.SetResult(response);
  249. }
  250. catch (Exception e)
  251. {
  252. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  253. }
  254. };
  255. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  256. return tcs.Task;
  257. }
  258. public void Send(AMessage message)
  259. {
  260. if (this.Id == 0)
  261. {
  262. throw new Exception("session已经被Dispose了");
  263. }
  264. this.SendMessage(message);
  265. }
  266. public void Reply<Response>(Response message) where Response : AResponse
  267. {
  268. if (this.Id == 0)
  269. {
  270. throw new Exception("session已经被Dispose了");
  271. }
  272. this.SendMessage(message);
  273. }
  274. private void SendMessage(object message)
  275. {
  276. //Log.Debug($"send: {MongoHelper.ToJson(message)}");
  277. Opcode opcode = this.network.Entity.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  278. ushort op = (ushort)opcode;
  279. byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
  280. if (messageBytes.Length > 100)
  281. {
  282. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  283. if (newMessageBytes.Length < messageBytes.Length)
  284. {
  285. messageBytes = newMessageBytes;
  286. op |= 0x8000;
  287. }
  288. }
  289. byte[] opcodeBytes = BitConverter.GetBytes(op);
  290. this.byteses[0] = opcodeBytes;
  291. this.byteses[1] = messageBytes;
  292. channel.Send(this.byteses);
  293. }
  294. public override void Dispose()
  295. {
  296. if (this.Id == 0)
  297. {
  298. return;
  299. }
  300. long id = this.Id;
  301. base.Dispose();
  302. this.channel.Dispose();
  303. this.network.Remove(id);
  304. }
  305. }
  306. }