You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
1.9 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. namespace Multiplayer
  6. {
  7. public class ServerManager : MonoBehaviour
  8. {
  9. [SerializeField]
  10. private bool StartOnAwake = true;
  11. [SerializeField]
  12. private int Port = 4444;
  13. public Dictionary<int, Player> AllPlayers;
  14. public NetworkServerSimple Server { get; private set; }
  15. private void Start()
  16. {
  17. if (StartOnAwake)
  18. StartServer();
  19. }
  20. [ContextMenu("Start Server")]
  21. public void StartServer()
  22. {
  23. StartServer(Port);
  24. }
  25. public void StartServer(int Port)
  26. {
  27. this.Port = Port;
  28. AllPlayers = new Dictionary<int, Player>();
  29. Server = new NetworkServerSimple();
  30. Server.RegisterHandler(MsgType.Connect, OnConnect);
  31. Server.RegisterHandler(MsgType.Disconnect, OnDisconnect);
  32. Server.Configure(ChannelConfig.DefaultTopology());
  33. Debug.Log("Starting Server on " + Port);
  34. Server.Listen(Port);
  35. }
  36. private void Update()
  37. {
  38. if (Server != null)
  39. Server.Update();
  40. }
  41. private void OnConnect(NetworkMessage msg)
  42. {
  43. Debug.Log("New Connection: \n Address: " + msg.conn.address + "\n ID: " + msg.conn.connectionId);
  44. msg.conn.Send(LoginMsgID.QueryName, new PlayerMsg((byte)msg.conn.connectionId));
  45. }
  46. private void OnDisconnect(NetworkMessage msg)
  47. {
  48. if (AllPlayers.ContainsKey(msg.conn.connectionId))
  49. {
  50. Debug.Log(AllPlayers[msg.conn.connectionId].Name + "has disconnected.");
  51. AllPlayers.Remove(msg.conn.connectionId);
  52. }
  53. else
  54. Debug.Log("Unkown player has disconnected.");
  55. }
  56. }
  57. }