ServerBehaviour.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. DataStreamWriter writer = new DataStreamWriter();
  73. m_Driver.BeginSend(m_Connections[id], out writer);
  74. netMsgController.SendData(code, netMsg, ref writer, this, id);
  75. m_Driver.EndSend(writer);
  76. }
  77. public void SendNetMsgToAllClients(uint code, NetMsg netMsg)
  78. {
  79. for (int i = 0; i < m_Connections.Length; i++)
  80. {
  81. Assert.IsTrue(m_Connections[i].IsCreated);
  82. SendNetMsgToClient(i, code, netMsg);
  83. }
  84. }
  85. public void OnDestroy()
  86. {
  87. if(!m_Driver.IsCreated) return;
  88. m_Driver.Dispose();
  89. m_Connections.Dispose();
  90. }
  91. void Update ()
  92. {
  93. if(!m_Driver.IsCreated) return;
  94. m_Driver.ScheduleUpdate().Complete();
  95. // CleanUpConnections
  96. for (int i = 0; i < m_Connections.Length; i++)
  97. {
  98. if (!m_Connections[i].IsCreated)
  99. {
  100. m_Connections.RemoveAtSwapBack(i);
  101. --i;
  102. }
  103. }
  104. // AcceptNewConnections
  105. NetworkConnection c;
  106. while ((c = m_Driver.Accept()) != default(NetworkConnection))
  107. {
  108. m_Connections.Add(c);
  109. if(debug) Debug.Log($"Accepted a connection (ID {c.InternalId})");
  110. GenericEvents.Trigger($"{eventStreamName}_ClientConnected", $"Accepted a connection (ID {c.InternalId})", c.InternalId);
  111. }
  112. DataStreamReader stream;
  113. for (int i = 0; i < m_Connections.Length; i++)
  114. {
  115. Assert.IsTrue(m_Connections[i].IsCreated);
  116. NetworkEvent.Type cmd;
  117. while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream)) != NetworkEvent.Type.Empty)
  118. {
  119. if (cmd == NetworkEvent.Type.Data)
  120. {
  121. //if(debug) Debug.Log("Server received data from client");
  122. netMsgController.ReceiveData(ref stream, this, i);
  123. }
  124. else if (cmd == NetworkEvent.Type.Disconnect)
  125. {
  126. if(debug) Debug.Log($"Client disconnected from server (ID {m_Connections[i].InternalId})");
  127. GenericEvents.Trigger($"{eventStreamName}_ClientDisconnected", $"Client disconnected from server (ID {m_Connections[i].InternalId})");
  128. m_Connections[i] = default(NetworkConnection);
  129. }
  130. }
  131. }
  132. }
  133. }
  134. }