NetServerComponentSystem.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Net;
  2. namespace ET.Server
  3. {
  4. [FriendOf(typeof(NetServerComponent))]
  5. public static class NetServerComponentSystem
  6. {
  7. [ObjectSystem]
  8. public class AwakeSystem: AwakeSystem<NetServerComponent, IPEndPoint>
  9. {
  10. protected override void Awake(NetServerComponent self, IPEndPoint address)
  11. {
  12. self.ServiceId = NetServices.Instance.AddService(new KService(address, ServiceType.Outer));
  13. NetServices.Instance.RegisterAcceptCallback(self.ServiceId, self.OnAccept);
  14. NetServices.Instance.RegisterReadCallback(self.ServiceId, self.OnRead);
  15. NetServices.Instance.RegisterErrorCallback(self.ServiceId, self.OnError);
  16. }
  17. }
  18. [ObjectSystem]
  19. public class NetKcpComponentDestroySystem: DestroySystem<NetServerComponent>
  20. {
  21. protected override void Destroy(NetServerComponent self)
  22. {
  23. NetServices.Instance.RemoveService(self.ServiceId);
  24. }
  25. }
  26. private static void OnError(this NetServerComponent self, long channelId, int error)
  27. {
  28. Session session = self.GetChild<Session>(channelId);
  29. if (session == null)
  30. {
  31. return;
  32. }
  33. session.Error = error;
  34. session.Dispose();
  35. }
  36. // 这个channelId是由CreateAcceptChannelId生成的
  37. private static void OnAccept(this NetServerComponent self, long channelId, IPEndPoint ipEndPoint)
  38. {
  39. Session session = self.AddChildWithId<Session, int>(channelId, self.ServiceId);
  40. session.RemoteAddress = ipEndPoint;
  41. if (self.DomainScene().SceneType == SceneType.BenchmarkServer)
  42. {
  43. return;
  44. }
  45. // 挂上这个组件,5秒就会删除session,所以客户端验证完成要删除这个组件。该组件的作用就是防止外挂一直连接不发消息也不进行权限验证
  46. session.AddComponent<SessionAcceptTimeoutComponent>();
  47. // 客户端连接,检查是否处于空闲,空闲则close
  48. if (ConstValue.SessionTimeoutTime > 0)
  49. {
  50. #pragma warning disable CS0162 // 检测到无法访问的代码
  51. session.AddComponent<SessionIdleCheckerComponent>();
  52. #pragma warning restore CS0162 // 检测到无法访问的代码
  53. }
  54. }
  55. private static void OnRead(this NetServerComponent self, long channelId, long actorId, object message)
  56. {
  57. Session session = self.GetChild<Session>(channelId);
  58. if (session == null)
  59. {
  60. return;
  61. }
  62. session.LastRecvTime = TimeHelper.ClientNow();
  63. OpcodeHelper.LogMsg(self.DomainZone(), message);
  64. EventSystem.Instance.Publish(NetServerComponentOnRead.Clone(session, message));
  65. }
  66. }
  67. }