ServerHandshakeController.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using KairoEngine.Core;
  5. namespace KairoEngine.Multiplayer
  6. {
  7. public class ServerHandshakeController : MonoBehaviour
  8. {
  9. public ServerBehaviour server;
  10. public string eventStreamName = "ServerEvents";
  11. private void Awake()
  12. {
  13. NetMsgEvents.StartListening($"{eventStreamName}_HandshakeReceived", OnEvent);
  14. }
  15. private void OnDestroy()
  16. {
  17. NetMsgEvents.StopListening($"{eventStreamName}_HandshakeReceived", OnEvent);
  18. }
  19. private void OnEvent(string text, int clientId, uint code, NetMsg netMsg)
  20. {
  21. if(server == null) return;
  22. // Accept the client handshake
  23. NetHandshakeMsg handshakeMsg = (NetHandshakeMsg)netMsg;
  24. Timer.ExecuteRealTime(100, ()=> {
  25. server.SendNetMsgToClient(clientId, (uint)NetOpCode.Handshake, handshakeMsg);
  26. });
  27. // Alert all clients of a new connection
  28. Timer.ExecuteRealTime(200, ()=> {
  29. NetClientConnectedMsg msg = new NetClientConnectedMsg();
  30. msg.playerName = handshakeMsg.playerName;
  31. server.SendNetMsgToAllClients((uint)NetOpCode.ClientConnected, msg);
  32. });
  33. }
  34. }
  35. }