Session.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 SessionEvent : ObjectEvent<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 void CallWithAction(ARequest request, Action<AResponse> action)
  139. {
  140. request.RpcId = ++RpcId;
  141. this.requestCallback[request.RpcId] = (message) =>
  142. {
  143. try
  144. {
  145. AResponse response = (AResponse)message;
  146. action(response);
  147. }
  148. catch (Exception e)
  149. {
  150. Log.Error(e.ToString());
  151. }
  152. };
  153. this.SendMessage(request);
  154. }
  155. /// <summary>
  156. /// Rpc调用,发送一个消息,等待返回一个消息
  157. /// </summary>
  158. public Task<AResponse> Call(ARequest request, bool isHotfix)
  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. this.SendMessage(request);
  181. return tcs.Task;
  182. }
  183. /// <summary>
  184. /// Rpc调用
  185. /// </summary>
  186. public Task<AResponse> Call(ARequest request, bool isHotfix, CancellationToken cancellationToken)
  187. {
  188. request.RpcId = ++RpcId;
  189. var tcs = new TaskCompletionSource<AResponse>();
  190. this.requestCallback[request.RpcId] = (message) =>
  191. {
  192. try
  193. {
  194. AResponse response = (AResponse)message;
  195. if (response.Error > 100)
  196. {
  197. tcs.SetException(new RpcException(response.Error, response.Message));
  198. return;
  199. }
  200. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  201. tcs.SetResult(response);
  202. }
  203. catch (Exception e)
  204. {
  205. tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
  206. }
  207. };
  208. cancellationToken.Register(() => { this.requestCallback.Remove(request.RpcId); });
  209. this.SendMessage(request);
  210. return tcs.Task;
  211. }
  212. /// <summary>
  213. /// Rpc调用,发送一个消息,等待返回一个消息
  214. /// </summary>
  215. public Task<Response> Call<Response>(ARequest request) where Response : AResponse
  216. {
  217. request.RpcId = ++RpcId;
  218. var tcs = new TaskCompletionSource<Response>();
  219. this.requestCallback[request.RpcId] = (message) =>
  220. {
  221. try
  222. {
  223. Response response = (Response)message;
  224. if (response.Error > 100)
  225. {
  226. tcs.SetException(new RpcException(response.Error, response.Message));
  227. return;
  228. }
  229. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  230. tcs.SetResult(response);
  231. }
  232. catch (Exception e)
  233. {
  234. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  235. }
  236. };
  237. this.SendMessage(request);
  238. return tcs.Task;
  239. }
  240. /// <summary>
  241. /// Rpc调用
  242. /// </summary>
  243. public Task<Response> Call<Response>(ARequest request, CancellationToken cancellationToken)
  244. where Response : AResponse
  245. {
  246. request.RpcId = ++RpcId;
  247. var tcs = new TaskCompletionSource<Response>();
  248. this.requestCallback[request.RpcId] = (message) =>
  249. {
  250. try
  251. {
  252. Response response = (Response)message;
  253. if (response.Error > 100)
  254. {
  255. tcs.SetException(new RpcException(response.Error, response.Message));
  256. return;
  257. }
  258. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  259. tcs.SetResult(response);
  260. }
  261. catch (Exception e)
  262. {
  263. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  264. }
  265. };
  266. cancellationToken.Register(() => { this.requestCallback.Remove(request.RpcId); });
  267. this.SendMessage(request);
  268. return tcs.Task;
  269. }
  270. public void Send(AMessage message)
  271. {
  272. if (this.Id == 0)
  273. {
  274. throw new Exception("session已经被Dispose了");
  275. }
  276. this.SendMessage(message);
  277. }
  278. public void Reply<Response>(Response message) where Response : AResponse
  279. {
  280. if (this.Id == 0)
  281. {
  282. throw new Exception("session已经被Dispose了");
  283. }
  284. this.SendMessage(message);
  285. }
  286. private void SendMessage(object message)
  287. {
  288. //Log.Debug($"send: {MongoHelper.ToJson(message)}");
  289. Opcode opcode = this.network.Parent.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  290. ushort op = (ushort)opcode;
  291. byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
  292. #if SERVER
  293. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  294. if (this.network.AppType == AppType.AllServer)
  295. {
  296. Session session = this.network.Parent.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  297. session.RunDecompressedBytes(op, messageBytes, 0, messageBytes.Length);
  298. return;
  299. }
  300. #endif
  301. byte[] opcodeBytes = BitConverter.GetBytes(op);
  302. this.byteses[0] = opcodeBytes;
  303. this.byteses[1] = messageBytes;
  304. channel.Send(this.byteses);
  305. }
  306. }
  307. }