NetworkComponent.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Common.Base;
  5. using Common.Helper;
  6. using Common.Network;
  7. using TNet;
  8. using UNet;
  9. namespace Model
  10. {
  11. public class NetworkComponent: Component<World>, IUpdate, IStart
  12. {
  13. private IService service;
  14. private int requestId;
  15. private readonly Dictionary<int, Action<byte[], bool>> requestCallback = new Dictionary<int, Action<byte[], bool>>();
  16. private readonly Dictionary<string, Queue<byte[]>> cache = new Dictionary<string, Queue<byte[]>>();
  17. private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
  18. {
  19. switch (protocol)
  20. {
  21. case NetworkProtocol.TCP:
  22. this.service = new TService(host, port);
  23. break;
  24. case NetworkProtocol.UDP:
  25. this.service = new UService(host, port);
  26. break;
  27. default:
  28. throw new ArgumentOutOfRangeException("protocol");
  29. }
  30. this.AcceptChannel();
  31. }
  32. public void Start()
  33. {
  34. this.Accept(World.Instance.Options.Host, World.Instance.Options.Port,
  35. World.Instance.Options.Protocol);
  36. }
  37. public void Update()
  38. {
  39. this.service.Update();
  40. }
  41. /// <summary>
  42. /// 接收连接
  43. /// </summary>
  44. private async void AcceptChannel()
  45. {
  46. while (true)
  47. {
  48. AChannel channel = await this.service.GetChannel();
  49. this.ProcessChannel(channel);
  50. }
  51. }
  52. /// <summary>
  53. /// 接收分发封包
  54. /// </summary>
  55. /// <param name="channel"></param>
  56. private async void ProcessChannel(AChannel channel)
  57. {
  58. while (true)
  59. {
  60. byte[] message = await channel.RecvAsync();
  61. Env env = new Env();
  62. env[EnvKey.Channel] = channel;
  63. env[EnvKey.Message] = message;
  64. int opcode = BitConverter.ToUInt16(message, 0);
  65. // 这个区间表示消息是rpc响应消息
  66. if (MessageTypeHelper.IsRpcResponseMessage(opcode))
  67. {
  68. int id = BitConverter.ToInt32(message, 2);
  69. this.RequestCallback(channel, id, message, true);
  70. continue;
  71. }
  72. // 如果是发给client的消息,说明这是gate server,需要根据unitid查到channel,进行发送
  73. if (MessageTypeHelper.IsServerMessage(opcode))
  74. {
  75. World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.GateRecvServerMessage, env);
  76. continue;
  77. }
  78. // 进行消息分发
  79. World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.LogicRecvMessage, env);
  80. }
  81. }
  82. public void SendAsync(string address, byte[] buffer)
  83. {
  84. AChannel channel = this.service.GetChannel(address);
  85. channel.SendAsync(buffer);
  86. }
  87. // 消息回调或者超时回调
  88. public void RequestCallback(AChannel channel, int id, byte[] buffer, bool isOK)
  89. {
  90. Action<byte[], bool> action;
  91. if (this.requestCallback.TryGetValue(id, out action))
  92. {
  93. action(buffer, isOK);
  94. }
  95. this.requestCallback.Remove(id);
  96. }
  97. /// <summary>
  98. /// Rpc请求
  99. /// </summary>
  100. public Task<T> Request<T, K>(AChannel channel, short type, K request, int waitTime = 0)
  101. {
  102. ++this.requestId;
  103. byte[] requestBuffer = MongoHelper.ToBson(request);
  104. byte[] typeBuffer = BitConverter.GetBytes(type);
  105. byte[] idBuffer = BitConverter.GetBytes(this.requestId);
  106. channel.SendAsync(new List<byte[]> { typeBuffer, idBuffer, requestBuffer });
  107. var tcs = new TaskCompletionSource<T>();
  108. this.requestCallback[this.requestId] = (e, b) =>
  109. {
  110. if (b)
  111. {
  112. T response = MongoHelper.FromBson<T>(e, 6);
  113. tcs.SetResult(response);
  114. }
  115. else
  116. {
  117. tcs.SetException(new Exception(string.Format("rpc timeout {0} {1}", type, MongoHelper.ToJson(request))));
  118. }
  119. };
  120. if (waitTime > 0)
  121. {
  122. this.service.Timer.Add(TimeHelper.Now() + waitTime, () =>
  123. {
  124. this.RequestCallback(channel, this.requestId, null, false);
  125. });
  126. }
  127. return tcs.Task;
  128. }
  129. /// <summary>
  130. /// Rpc响应
  131. /// </summary>
  132. public void Response<T>(AChannel channel, short type, int id, T response)
  133. {
  134. byte[] responseBuffer = MongoHelper.ToBson(response);
  135. byte[] typeBuffer = BitConverter.GetBytes(type);
  136. byte[] idBuffer = BitConverter.GetBytes(id);
  137. channel.SendAsync(new List<byte[]> { typeBuffer, idBuffer, responseBuffer });
  138. }
  139. }
  140. }