NetworkComponent.cs 4.3 KB

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