GateNetworkComponent.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using Common.Base;
  3. using Common.Network;
  4. using TNet;
  5. using UNet;
  6. namespace Model
  7. {
  8. /// <summary>
  9. /// gate对外连接使用
  10. /// </summary>
  11. public class GateNetworkComponent: Component<World>, IUpdate, IStart
  12. {
  13. private IService service;
  14. private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
  15. {
  16. switch (protocol)
  17. {
  18. case NetworkProtocol.TCP:
  19. this.service = new TService(host, port);
  20. break;
  21. case NetworkProtocol.UDP:
  22. this.service = new UService(host, port);
  23. break;
  24. default:
  25. throw new ArgumentOutOfRangeException("protocol");
  26. }
  27. this.AcceptChannel();
  28. }
  29. public void Start()
  30. {
  31. this.Accept(World.Instance.Options.GateHost, World.Instance.Options.GatePort,
  32. World.Instance.Options.Protocol);
  33. }
  34. public void Update()
  35. {
  36. this.service.Update();
  37. }
  38. /// <summary>
  39. /// 接收连接
  40. /// </summary>
  41. private async void AcceptChannel()
  42. {
  43. while (true)
  44. {
  45. AChannel channel = await this.service.GetChannel();
  46. ProcessChannel(channel);
  47. }
  48. }
  49. /// <summary>
  50. /// 接收分发封包
  51. /// </summary>
  52. /// <param name="channel"></param>
  53. private static async void ProcessChannel(AChannel channel)
  54. {
  55. while (true)
  56. {
  57. byte[] message = await channel.RecvAsync();
  58. Env env = new Env();
  59. env[EnvKey.Channel] = channel;
  60. env[EnvKey.Message] = message;
  61. // 进行消息分发
  62. int opcode = BitConverter.ToUInt16(message, 0);
  63. if (!MessageTypeHelper.IsClientMessage(opcode))
  64. {
  65. ChannelUnitInfoComponent channelUnitInfoComponent = channel.GetComponent<ChannelUnitInfoComponent>();
  66. byte[] idBuffer = channelUnitInfoComponent.PlayerId.ToByteArray();
  67. byte[] buffer = new byte[message.Length + 12];
  68. Array.Copy(message, 0, buffer, 0, 4);
  69. Array.Copy(idBuffer, 0, buffer, 4, idBuffer.Length);
  70. Array.Copy(message, 4, buffer, 4 + 12, message.Length - 4);
  71. continue;
  72. }
  73. World.Instance.GetComponent<EventComponent<MessageAttribute>>().RunAsync(opcode, env);
  74. }
  75. }
  76. }
  77. }