ServerBehaviour.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. using UnityEngine;
  2. using UnityEngine.Assertions;
  3. using Unity.Collections;
  4. using Unity.Networking.Transport;
  5. using KairoEngine.Core;
  6. using Sirenix.OdinInspector;
  7. namespace KairoEngine.Multiplayer
  8. {
  9. [HideMonoScript]
  10. public class ServerBehaviour : MonoBehaviour
  11. {
  12. public NetMsgController netMsgController;
  13. public string eventStreamName = "ServerEvents";
  14. public ushort port = 9000;
  15. public int players = 4;
  16. public bool autoStart = true;
  17. public bool debug = false;
  18. public NetworkDriver m_Driver;
  19. public NativeList<NetworkConnection> m_Connections;
  20. private bool locked = false;
  21. private void Awake()
  22. {
  23. if(netMsgController == null)
  24. {
  25. Debug.LogError("Server is missing NetMsgController!", this);
  26. return;
  27. }
  28. }
  29. private void Start ()
  30. {
  31. if(autoStart) StartServer();
  32. }
  33. public void StartServer()
  34. {
  35. if(locked) return;
  36. if(netMsgController == null)
  37. {
  38. Debug.LogError("Server cannot start with missing NetMsgController!", this);
  39. return;
  40. }
  41. m_Driver = NetworkDriver.Create();
  42. var endpoint = NetworkEndPoint.AnyIpv4;
  43. endpoint.Port = port;
  44. if (m_Driver.Bind(endpoint) != 0)
  45. {
  46. if(debug) Debug.Log($"Failed to bind to port {port}");
  47. GenericEvents.Trigger($"{eventStreamName}_PortError", $"Failed to bind to port {port}");
  48. }
  49. else
  50. {
  51. m_Driver.Listen();
  52. if(debug) Debug.Log($"Server listening on port {port}");
  53. GenericEvents.Trigger($"{eventStreamName}_Listening", $"Server listening on port {port}");
  54. locked = true;
  55. }
  56. m_Connections = new NativeList<NetworkConnection>(players, Allocator.Persistent);
  57. }
  58. public void StopServer()
  59. {
  60. NetDisconnectMsg netDisconnectMsg = new NetDisconnectMsg();
  61. SendNetMsgToAllClients((uint)NetOpCode.Disconnect, netDisconnectMsg);
  62. Timer.ExecuteRealTime(500, () => {
  63. if(debug) Debug.Log($"Server has stopped");
  64. GenericEvents.Trigger($"{eventStreamName}_Stopped", $"Server has stopped");
  65. m_Driver.Dispose();
  66. m_Connections.Dispose();
  67. locked = false;
  68. });
  69. }
  70. public void SendNetMsgToClient(int id, uint code, NetMsg netMsg)
  71. {
  72. netMsgController.SendData(code, netMsg, this, id);
  73. }
  74. public void SendNetMsgToAllClients(uint code, NetMsg netMsg)
  75. {
  76. for (int i = 0; i < m_Connections.Length; i++)
  77. {
  78. Assert.IsTrue(m_Connections[i].IsCreated);
  79. SendNetMsgToClient(i, code, netMsg);
  80. }
  81. }
  82. public void OnDestroy()
  83. {
  84. if(!m_Driver.IsCreated) return;
  85. m_Driver.Dispose();
  86. m_Connections.Dispose();
  87. }
  88. void Update ()
  89. {
  90. if(!m_Driver.IsCreated) return;
  91. m_Driver.ScheduleUpdate().Complete();
  92. // CleanUpConnections
  93. for (int i = 0; i < m_Connections.Length; i++)
  94. {
  95. if (!m_Connections[i].IsCreated)
  96. {
  97. m_Connections.RemoveAtSwapBack(i);
  98. --i;
  99. }
  100. }
  101. // AcceptNewConnections
  102. NetworkConnection c;
  103. while ((c = m_Driver.Accept()) != default(NetworkConnection))
  104. {
  105. m_Connections.Add(c);
  106. if(debug) Debug.Log($"Accepted a connection (ID {c.InternalId})");
  107. GenericEvents.Trigger($"{eventStreamName}_ClientConnected", $"Accepted a connection (ID {c.InternalId})", c.InternalId);
  108. }
  109. DataStreamReader stream;
  110. for (int i = 0; i < m_Connections.Length; i++)
  111. {
  112. Assert.IsTrue(m_Connections[i].IsCreated);
  113. NetworkEvent.Type cmd;
  114. while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream)) != NetworkEvent.Type.Empty)
  115. {
  116. if (cmd == NetworkEvent.Type.Data)
  117. {
  118. //if(debug) Debug.Log("Server received data from client");
  119. netMsgController.ReceiveData(ref stream, this, i);
  120. }
  121. else if (cmd == NetworkEvent.Type.Disconnect)
  122. {
  123. if(debug) Debug.Log($"Client disconnected from server (ID {m_Connections[i].InternalId})");
  124. GenericEvents.Trigger($"{eventStreamName}_ClientDisconnected", $"Client disconnected from server (ID {m_Connections[i].InternalId})");
  125. m_Connections[i] = default(NetworkConnection);
  126. }
  127. }
  128. }
  129. }
  130. }
  131. }