Session.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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<Response> Call<Response>(ARequest request) where Response : AResponse
  147. {
  148. request.RpcId = ++RpcId;
  149. this.SendMessage(request);
  150. var tcs = new TaskCompletionSource<Response>();
  151. this.requestCallback[RpcId] = (message) =>
  152. {
  153. try
  154. {
  155. Response response = (Response)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: {typeof(Response).FullName}", e));
  167. }
  168. };
  169. return tcs.Task;
  170. }
  171. public void Send(AMessage message)
  172. {
  173. if (this.Id == 0)
  174. {
  175. throw new Exception("session已经被Dispose了");
  176. }
  177. this.SendMessage(message);
  178. }
  179. public void Reply<Response>(Response message) where Response : AResponse
  180. {
  181. if (this.Id == 0)
  182. {
  183. throw new Exception("session已经被Dispose了");
  184. }
  185. this.SendMessage(message);
  186. }
  187. private void SendMessage(object message)
  188. {
  189. //Log.Debug($"send: {MongoHelper.ToJson(message)}");
  190. Opcode opcode = this.network.Entity.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  191. ushort op = (ushort)opcode;
  192. byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
  193. if (messageBytes.Length > 100)
  194. {
  195. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  196. if (newMessageBytes.Length < messageBytes.Length)
  197. {
  198. messageBytes = newMessageBytes;
  199. op |= 0x8000;
  200. }
  201. }
  202. byte[] opcodeBytes = BitConverter.GetBytes(op);
  203. this.byteses[0] = opcodeBytes;
  204. this.byteses[1] = messageBytes;
  205. channel.Send(this.byteses);
  206. }
  207. public override void Dispose()
  208. {
  209. if (this.Id == 0)
  210. {
  211. return;
  212. }
  213. long id = this.Id;
  214. base.Dispose();
  215. this.channel.Dispose();
  216. this.network.Remove(id);
  217. }
  218. }
  219. }