ClientHandshakeController.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. [HideMonoScript]
  9. public class ClientHandshakeController : MonoBehaviour
  10. {
  11. public ClientBehaviour client;
  12. public NetworkTick networkTick;
  13. private bool waitingForHandshake = false;
  14. private void Awake()
  15. {
  16. GenericEvents.StartListening($"{client.eventStreamName}_Connected", OnEvent);
  17. NetMsgEvents.StartListening($"{client.eventStreamName}_HandshakeAccepted", OnHandshakeAccepted);
  18. }
  19. private void OnDestroy()
  20. {
  21. GenericEvents.StopListening($"{client.eventStreamName}_Connected", OnEvent);
  22. NetMsgEvents.StopListening($"{client.eventStreamName}_HandshakeAccepted", OnHandshakeAccepted);
  23. }
  24. private void OnEvent(string text)
  25. {
  26. if(client == null) return;
  27. NetHandshakeMsg handshakeMsg = new NetHandshakeMsg();
  28. handshakeMsg.playerName = client.playerName;
  29. Timer.ExecuteRealTime(100, ()=> {
  30. waitingForHandshake = true;
  31. client.SendNetMsgToServer(((uint)NetOpCode.Handshake), handshakeMsg);
  32. });
  33. }
  34. private void OnHandshakeAccepted(string text, int clientId, uint code, NetMsg netMsg)
  35. {
  36. if(!waitingForHandshake) return;
  37. waitingForHandshake = false;
  38. NetAcceptHandshakeMsg netAcceptHandshakeMsg = (NetAcceptHandshakeMsg)netMsg;
  39. if(networkTick != null) networkTick.ChangeCurrentTick((int)netAcceptHandshakeMsg.tick);
  40. }
  41. }
  42. }