Session.cs 7.7 KB

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