using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; namespace Multiplayer { public class ServerManager : MonoBehaviour { [SerializeField] private bool StartOnAwake = true; [SerializeField] private int Port = 4444; public Dictionary AllPlayers; public NetworkServerSimple Server { get; private set; } private void Start() { if (StartOnAwake) StartServer(); } [ContextMenu("Start Server")] public void StartServer() { StartServer(Port); } public void StartServer(int Port) { this.Port = Port; AllPlayers = new Dictionary(); Server = new NetworkServerSimple(); Server.RegisterHandler(MsgType.Connect, OnConnect); Server.RegisterHandler(MsgType.Disconnect, OnDisconnect); Server.Configure(ChannelConfig.DefaultTopology()); Debug.Log("Starting Server on " + Port); Server.Listen(Port); } private void Update() { if (Server != null) Server.Update(); } private void OnConnect(NetworkMessage msg) { Debug.Log("New Connection: \n Address: " + msg.conn.address + "\n ID: " + msg.conn.connectionId); msg.conn.Send(LoginMsgID.QueryName, new PlayerMsg((byte)msg.conn.connectionId)); } private void OnDisconnect(NetworkMessage msg) { if (AllPlayers.ContainsKey(msg.conn.connectionId)) { Debug.Log(AllPlayers[msg.conn.connectionId].Name + "has disconnected."); AllPlayers.Remove(msg.conn.connectionId); } else Debug.Log("Unkown player has disconnected."); } } }