NetworkComponent.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 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>>()
  76. .Run(EventType.GateRecvServerMessage, env);
  77. continue;
  78. }
  79. // 进行消息分发
  80. World.Instance.GetComponent<EventComponent<EventAttribute>>()
  81. .Run(EventType.LogicRecvMessage, env);
  82. }
  83. }
  84. public void SendAsync(string address, byte[] buffer)
  85. {
  86. AChannel channel = this.service.GetChannel(address);
  87. channel.SendAsync(buffer);
  88. }
  89. // 消息回调或者超时回调
  90. public void RequestCallback(AChannel channel, int id, byte[] buffer, bool isOK)
  91. {
  92. Action<byte[], bool> action;
  93. if (this.requestCallback.TryGetValue(id, out action))
  94. {
  95. action(buffer, isOK);
  96. }
  97. this.requestCallback.Remove(id);
  98. }
  99. /// <summary>
  100. /// Rpc请求
  101. /// </summary>
  102. public Task<T> Request<T, K>(AChannel channel, short type, K request, int waitTime = 0)
  103. {
  104. ++this.requestId;
  105. byte[] requestBuffer = MongoHelper.ToBson(request);
  106. byte[] typeBuffer = BitConverter.GetBytes(type);
  107. byte[] idBuffer = BitConverter.GetBytes(this.requestId);
  108. channel.SendAsync(new List<byte[]> { typeBuffer, idBuffer, requestBuffer });
  109. var tcs = new TaskCompletionSource<T>();
  110. this.requestCallback[this.requestId] = (e, b) =>
  111. {
  112. if (b)
  113. {
  114. T response = MongoHelper.FromBson<T>(e, 6);
  115. tcs.SetResult(response);
  116. }
  117. else
  118. {
  119. tcs.SetException(
  120. new Exception(string.Format("rpc timeout {0} {1}", type,
  121. MongoHelper.ToJson(request))));
  122. }
  123. };
  124. if (waitTime > 0)
  125. {
  126. this.service.Timer.Add(TimeHelper.Now() + waitTime,
  127. () => { this.RequestCallback(channel, this.requestId, null, false); });
  128. }
  129. return tcs.Task;
  130. }
  131. /// <summary>
  132. /// Rpc响应
  133. /// </summary>
  134. public void Response<T>(AChannel channel, short type, int id, T response)
  135. {
  136. byte[] responseBuffer = MongoHelper.ToBson(response);
  137. byte[] typeBuffer = BitConverter.GetBytes(type);
  138. byte[] idBuffer = BitConverter.GetBytes(id);
  139. channel.SendAsync(new List<byte[]> { typeBuffer, idBuffer, responseBuffer });
  140. }
  141. }
  142. }