Session.cs 7.8 KB

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