ServerStatus.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. namespace KairoEngine.Multiplayer
  6. {
  7. public enum ServerState
  8. {
  9. Offline,
  10. Online
  11. }
  12. [HideMonoScript]
  13. public class ServerStatus : MonoBehaviour
  14. {
  15. public ServerBehaviour server;
  16. [ReadOnly] public ServerState state;
  17. [ReadOnly] public int clientCount;
  18. [ReadOnly] public int maxClients;
  19. [ReadOnly] public float uptime = 0;
  20. [ReadOnly] public string ipAddress;
  21. [ReadOnly] public int packetsSent;
  22. [ReadOnly] public int packetsReceived;
  23. private void OnEnable()
  24. {
  25. NetMsgEvents.StartListening($"{server.eventStreamName}_InvalidOpCode", OnReceivePacket);
  26. NetMsgEvents.StartListening($"{server.eventStreamName}_SendingDisconnectMessageToClient", OnSentPacket);
  27. NetMsgEvents.StartListening($"{server.eventStreamName}_ClientDisconnect", OnReceivePacket);
  28. NetMsgEvents.StartListening($"{server.eventStreamName}_HandshakeReceived", OnReceivePacket);
  29. NetMsgEvents.StartListening($"{server.eventStreamName}_AcceptingHandshake", OnSentPacket);
  30. }
  31. private void OnDisable()
  32. {
  33. NetMsgEvents.StopListening($"{server.eventStreamName}_InvalidOpCode", OnReceivePacket);
  34. NetMsgEvents.StopListening($"{server.eventStreamName}_SendingDisconnectMessageToClient", OnSentPacket);
  35. NetMsgEvents.StopListening($"{server.eventStreamName}_ClientDisconnect", OnReceivePacket);
  36. NetMsgEvents.StopListening($"{server.eventStreamName}_HandshakeReceived", OnReceivePacket);
  37. NetMsgEvents.StopListening($"{server.eventStreamName}_AcceptingHandshake", OnSentPacket);
  38. }
  39. private void Update()
  40. {
  41. if(server.m_Driver.IsCreated == false)
  42. {
  43. state = ServerState.Offline;
  44. clientCount = 0;
  45. uptime = 0;
  46. packetsSent = 0;
  47. packetsReceived = 0;
  48. }
  49. else
  50. {
  51. state = ServerState.Online;
  52. clientCount = 0;
  53. for (int i = 0; i < server.m_Connections.Length; i++)
  54. {
  55. if(server.m_Connections[i].IsCreated) clientCount += 1;
  56. }
  57. uptime += Time.deltaTime;
  58. }
  59. maxClients = server.players;
  60. }
  61. private void OnSentPacket(string text, int clientId, uint code, NetMsg netMsg) => packetsSent += 1;
  62. private void OnReceivePacket(string text, int clientId, uint code, NetMsg netMsg) => packetsReceived += 1;
  63. }
  64. }