ClientStatus.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. using KairoEngine.Core;
  6. namespace KairoEngine.Multiplayer
  7. {
  8. public enum ClientState
  9. {
  10. Disconnected,
  11. Connecting,
  12. Connected,
  13. }
  14. [HideMonoScript]
  15. public class ClientStatus : MonoBehaviour
  16. {
  17. public ClientBehaviour client;
  18. [ReadOnly] public ClientState state;
  19. [ReadOnly] public int peerCount;
  20. [ReadOnly] public float uptime = 0;
  21. [ReadOnly] public int tick = 0;
  22. [ReadOnly] public string serverAddress;
  23. [ReadOnly] public int packetsSent;
  24. [ReadOnly] public int packetsReceived;
  25. private void OnEnable()
  26. {
  27. NetMsgEvents.StartListening($"{client.eventStreamName}_InvalidOpCode", OnReceivePacket);
  28. NetMsgEvents.StartListening($"{client.eventStreamName}_SendingDisconnectMessageToServer", OnSentPacket);
  29. NetMsgEvents.StartListening($"{client.eventStreamName}_ServerDisconnect", OnReceivePacket);
  30. NetMsgEvents.StartListening($"{client.eventStreamName}_SendingHandshake", OnSentPacket);
  31. NetMsgEvents.StartListening($"{client.eventStreamName}_HandshakeAccepted", OnReceivePacket);
  32. GenericEvents.StartListening($"{client.eventStreamName}_OnTick", OnTick);
  33. }
  34. private void OnDisable()
  35. {
  36. NetMsgEvents.StopListening($"{client.eventStreamName}_InvalidOpCode", OnReceivePacket);
  37. NetMsgEvents.StopListening($"{client.eventStreamName}_SendingDisconnectMessageToServer", OnSentPacket);
  38. NetMsgEvents.StopListening($"{client.eventStreamName}_ServerDisconnect", OnReceivePacket);
  39. NetMsgEvents.StopListening($"{client.eventStreamName}_SendingHandshake", OnSentPacket);
  40. NetMsgEvents.StopListening($"{client.eventStreamName}_HandshakeAccepted", OnReceivePacket);
  41. }
  42. private void Update()
  43. {
  44. if(client.m_Driver.IsCreated == false)
  45. {
  46. state = ClientState.Disconnected;
  47. peerCount = 0;
  48. uptime = 0;
  49. packetsSent = 0;
  50. packetsReceived = 0;
  51. }
  52. else
  53. {
  54. state = ClientState.Connected;
  55. peerCount = 0;
  56. uptime += Time.deltaTime;
  57. }
  58. }
  59. private void OnSentPacket(string text, int clientId, uint code, NetMsg netMsg) => packetsSent += 1;
  60. private void OnReceivePacket(string text, int clientId, uint code, NetMsg netMsg) => packetsReceived += 1;
  61. private void OnTick(int newTick) => tick = newTick;
  62. }
  63. }