ServerHandshakeController.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 NetworkTick networkTick;
  11. public string eventStreamName = "ServerEvents";
  12. private void OnEnable()
  13. {
  14. NetMsgEvents.StartListening($"{eventStreamName}_HandshakeReceived", OnEvent);
  15. }
  16. private void OnDestroy()
  17. {
  18. NetMsgEvents.StopListening($"{eventStreamName}_HandshakeReceived", OnEvent);
  19. }
  20. private void OnEvent(string text, int clientId, uint code, NetMsg netMsg)
  21. {
  22. if(server == null) return;
  23. // Accept the client handshake
  24. NetHandshakeMsg netHandshakeMsg = (NetHandshakeMsg)netMsg;
  25. NetAcceptHandshakeMsg netAcceptHandshakeMsg = new NetAcceptHandshakeMsg();
  26. if(netHandshakeMsg != null) netAcceptHandshakeMsg.playerName = netHandshakeMsg.playerName;
  27. if(networkTick != null) netAcceptHandshakeMsg.tick = (uint)networkTick.tick;
  28. Timer.ExecuteRealTime(100, ()=> {
  29. server.SendNetMsgToClient(clientId, (uint)NetOpCode.AcceptHandshake, netAcceptHandshakeMsg);
  30. });
  31. // Alert all clients of a new connection
  32. Timer.ExecuteRealTime(200, ()=> {
  33. NetClientConnectedMsg msg = new NetClientConnectedMsg();
  34. msg.playerName = netAcceptHandshakeMsg.playerName;
  35. server.SendNetMsgToAllClients((uint)NetOpCode.ClientConnected, msg);
  36. });
  37. }
  38. }
  39. }