ServerStatus.cs 3.0 KB

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