Session.cs 7.5 KB

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