Session.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace Model
  7. {
  8. public sealed class Session : Entity
  9. {
  10. private static uint RpcId { get; set; }
  11. private readonly NetworkComponent network;
  12. private readonly Dictionary<uint, Action<object>> requestCallback = new Dictionary<uint, Action<object>>();
  13. private readonly AChannel channel;
  14. private readonly List<byte[]> byteses = new List<byte[]>() {new byte[0], new byte[0]};
  15. public Session(NetworkComponent network, AChannel channel)
  16. {
  17. this.network = network;
  18. this.channel = channel;
  19. this.StartRecv();
  20. }
  21. public IPEndPoint RemoteAddress
  22. {
  23. get
  24. {
  25. return this.channel.RemoteAddress;
  26. }
  27. }
  28. public ChannelType ChannelType
  29. {
  30. get
  31. {
  32. return this.channel.ChannelType;
  33. }
  34. }
  35. private async void StartRecv()
  36. {
  37. while (true)
  38. {
  39. if (this.Id == 0)
  40. {
  41. return;
  42. }
  43. Packet packet;
  44. try
  45. {
  46. packet = await this.channel.Recv();
  47. if (this.Id == 0)
  48. {
  49. return;
  50. }
  51. }
  52. catch (Exception e)
  53. {
  54. Log.Error(e.ToString());
  55. continue;
  56. }
  57. if (packet.Length < 2)
  58. {
  59. Log.Error($"message error length < 2, ip: {this.RemoteAddress}");
  60. this.network.Remove(this.Id);
  61. return;
  62. }
  63. ushort opcode = BitConverter.ToUInt16(packet.Bytes, 0);
  64. try
  65. {
  66. this.RunDecompressedBytes(opcode, packet.Bytes, 2, packet.Length);
  67. }
  68. catch (Exception e)
  69. {
  70. Log.Error(e.ToString());
  71. }
  72. }
  73. }
  74. private void RunDecompressedBytes(ushort opcode, byte[] messageBytes, int offset, int count)
  75. {
  76. object message;
  77. Opcode op;
  78. try
  79. {
  80. op = (Opcode)opcode;
  81. Type messageType = this.network.Entity.GetComponent<OpcodeTypeComponent>().GetType(op);
  82. message = this.network.MessagePacker.DeserializeFrom(messageType, messageBytes, offset, count - offset);
  83. }
  84. catch (Exception e)
  85. {
  86. Log.Error($"message deserialize error, ip: {this.RemoteAddress} {opcode} {e}");
  87. this.network.Remove(this.Id);
  88. return;
  89. }
  90. //Log.Debug($"recv: {MongoHelper.ToJson(message)}");
  91. AResponse response = message as AResponse;
  92. if (response != null)
  93. {
  94. // rpcFlag>0 表示这是一个rpc响应消息
  95. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  96. Action<object> action;
  97. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  98. {
  99. return;
  100. }
  101. this.requestCallback.Remove(response.RpcId);
  102. action(message);
  103. return;
  104. }
  105. this.network.MessageDispatcher.Dispatch(this, op, offset, messageBytes, (AMessage)message);
  106. }
  107. /// <summary>
  108. /// Rpc调用
  109. /// </summary>
  110. public void CallWithAction(ARequest request, Action<AResponse> action)
  111. {
  112. request.RpcId = ++RpcId;
  113. this.requestCallback[request.RpcId] = (message) =>
  114. {
  115. try
  116. {
  117. AResponse response = (AResponse)message;
  118. action(response);
  119. }
  120. catch (Exception e)
  121. {
  122. Log.Error(e.ToString());
  123. }
  124. };
  125. this.SendMessage(request);
  126. }
  127. /// <summary>
  128. /// Rpc调用,发送一个消息,等待返回一个消息
  129. /// </summary>
  130. public Task<AResponse> Call(ARequest request, bool isHotfix)
  131. {
  132. request.RpcId = ++RpcId;
  133. var tcs = new TaskCompletionSource<AResponse>();
  134. this.requestCallback[request.RpcId] = (message) =>
  135. {
  136. try
  137. {
  138. AResponse response = (AResponse)message;
  139. if (response.Error > 100)
  140. {
  141. tcs.SetException(new RpcException(response.Error, response.Message));
  142. return;
  143. }
  144. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  145. tcs.SetResult(response);
  146. }
  147. catch (Exception e)
  148. {
  149. tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
  150. }
  151. };
  152. this.SendMessage(request);
  153. return tcs.Task;
  154. }
  155. /// <summary>
  156. /// Rpc调用
  157. /// </summary>
  158. public Task<AResponse> Call(ARequest request, bool isHotfix, CancellationToken cancellationToken)
  159. {
  160. request.RpcId = ++RpcId;
  161. var tcs = new TaskCompletionSource<AResponse>();
  162. this.requestCallback[request.RpcId] = (message) =>
  163. {
  164. try
  165. {
  166. AResponse response = (AResponse)message;
  167. if (response.Error > 100)
  168. {
  169. tcs.SetException(new RpcException(response.Error, response.Message));
  170. return;
  171. }
  172. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  173. tcs.SetResult(response);
  174. }
  175. catch (Exception e)
  176. {
  177. tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
  178. }
  179. };
  180. cancellationToken.Register(() => { this.requestCallback.Remove(request.RpcId); });
  181. this.SendMessage(request);
  182. return tcs.Task;
  183. }
  184. /// <summary>
  185. /// Rpc调用,发送一个消息,等待返回一个消息
  186. /// </summary>
  187. public Task<Response> Call<Response>(ARequest request) where Response : AResponse
  188. {
  189. request.RpcId = ++RpcId;
  190. var tcs = new TaskCompletionSource<Response>();
  191. this.requestCallback[request.RpcId] = (message) =>
  192. {
  193. try
  194. {
  195. Response response = (Response)message;
  196. if (response.Error > 100)
  197. {
  198. tcs.SetException(new RpcException(response.Error, response.Message));
  199. return;
  200. }
  201. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  202. tcs.SetResult(response);
  203. }
  204. catch (Exception e)
  205. {
  206. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  207. }
  208. };
  209. this.SendMessage(request);
  210. return tcs.Task;
  211. }
  212. /// <summary>
  213. /// Rpc调用
  214. /// </summary>
  215. public Task<Response> Call<Response>(ARequest request, CancellationToken cancellationToken)
  216. where Response : AResponse
  217. {
  218. request.RpcId = ++RpcId;
  219. var tcs = new TaskCompletionSource<Response>();
  220. this.requestCallback[request.RpcId] = (message) =>
  221. {
  222. try
  223. {
  224. Response response = (Response)message;
  225. if (response.Error > 100)
  226. {
  227. tcs.SetException(new RpcException(response.Error, response.Message));
  228. return;
  229. }
  230. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  231. tcs.SetResult(response);
  232. }
  233. catch (Exception e)
  234. {
  235. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  236. }
  237. };
  238. cancellationToken.Register(() => { this.requestCallback.Remove(request.RpcId); });
  239. this.SendMessage(request);
  240. return tcs.Task;
  241. }
  242. public void Send(AMessage message)
  243. {
  244. if (this.Id == 0)
  245. {
  246. throw new Exception("session已经被Dispose了");
  247. }
  248. this.SendMessage(message);
  249. }
  250. public void Reply<Response>(Response message) where Response : AResponse
  251. {
  252. if (this.Id == 0)
  253. {
  254. throw new Exception("session已经被Dispose了");
  255. }
  256. this.SendMessage(message);
  257. }
  258. private void SendMessage(object message)
  259. {
  260. //Log.Debug($"send: {MongoHelper.ToJson(message)}");
  261. Opcode opcode = this.network.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  262. ushort op = (ushort)opcode;
  263. byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
  264. #if SERVER
  265. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  266. if (this.network.AppType == AppType.AllServer)
  267. {
  268. Session session = this.network.GetComponent<NetInnerComponent>().Get(this.RemoteAddress.ToString());
  269. session.RunDecompressedBytes(op, messageBytes, 0, messageBytes.Length);
  270. return;
  271. }
  272. #endif
  273. byte[] opcodeBytes = BitConverter.GetBytes(op);
  274. this.byteses[0] = opcodeBytes;
  275. this.byteses[1] = messageBytes;
  276. channel.Send(this.byteses);
  277. }
  278. public override void Dispose()
  279. {
  280. if (this.Id == 0)
  281. {
  282. return;
  283. }
  284. long id = this.Id;
  285. base.Dispose();
  286. this.channel.Dispose();
  287. this.network.Remove(id);
  288. }
  289. }
  290. }