ClientList.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. [HideMonoScript]
  9. public class ClientList : MonoBehaviour
  10. {
  11. public ServerBehaviour server;
  12. public List<ClientData> clients;
  13. private void OnEnable()
  14. {
  15. NetMsgEvents.StartListening($"{server.eventStreamName}_AcceptingHandshake", OnServerAcceptingHandshakeEvent);
  16. NetMsgEvents.StartListening($"{server.eventStreamName}_ClientDisconnect", OnServerClientDisconnectEvent);
  17. }
  18. private void OnDisable()
  19. {
  20. NetMsgEvents.StopListening($"{server.eventStreamName}_AcceptingHandshake", OnServerAcceptingHandshakeEvent);
  21. NetMsgEvents.StartListening($"{server.eventStreamName}_ClientDisconnect", OnServerClientDisconnectEvent);
  22. }
  23. private void OnServerAcceptingHandshakeEvent(string text, int clientId, uint code, NetMsg netMsg)
  24. {
  25. NetAcceptHandshakeMsg handshake = (NetAcceptHandshakeMsg)netMsg;
  26. bool registered = false;
  27. for (int i = 0; i < clients.Count; i++)
  28. {
  29. if(clients[i].playerName == handshake.playerName)
  30. {
  31. clients[i].connectionId = clientId;
  32. clients[i].isConnected = true;
  33. registered = true;
  34. }
  35. }
  36. if(!registered) clients.Add(new ClientData(clientId, handshake.playerName, true));
  37. }
  38. private void OnServerClientDisconnectEvent(string text, int clientId, uint code, NetMsg netMsg)
  39. {
  40. NetDisconnectMsg disconnectMsg = (NetDisconnectMsg)netMsg;
  41. for (int i = 0; i < clients.Count; i++)
  42. {
  43. if(clients[i].connectionId == clientId)
  44. {
  45. clients[i].connectionId = -1;
  46. clients[i].isConnected = false;
  47. }
  48. }
  49. }
  50. public ClientData GetClientData(int connectionId)
  51. {
  52. for (int i = 0; i < clients.Count; i++)
  53. {
  54. if(clients[i].connectionId == connectionId) return clients[i];
  55. }
  56. return null;
  57. }
  58. }
  59. }