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.

86 lines
2.0 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 LoginManager loginManager;
  16. private void Start()
  17. {
  18. if (StartOnAwake)
  19. StartServer();
  20. }
  21. [ContextMenu("Start Server")]
  22. public void StartServer()
  23. {
  24. StartServer(Port);
  25. }
  26. public void StartServer(int Port)
  27. {
  28. this.Port = Port;
  29. AllPlayers = new Dictionary<int, Player>();
  30. Server = new NetworkServerSimple();
  31. Server.RegisterHandler(MsgType.Connect, OnConnect);
  32. Server.RegisterHandler(MsgType.Disconnect, OnDisconnect);
  33. Server.Configure(ChannelConfig.DefaultTopology());
  34. Debug.Log("Starting Server on " + Port);
  35. loginManager = new LoginManager(this);
  36. Server.Listen(Port);
  37. }
  38. private void Update()
  39. {
  40. if (Server != null)
  41. Server.Update();
  42. }
  43. private void OnConnect(NetworkMessage msg)
  44. {
  45. Debug.Log("New Connection: \n Address: " + msg.conn.address + "\n ID: " + msg.conn.connectionId);
  46. //msg.conn.Send(LoginMsgID.QueryName, new PlayerMsg((byte)msg.conn.connectionId));
  47. }
  48. private void OnDisconnect(NetworkMessage msg)
  49. {
  50. if (AllPlayers.ContainsKey(msg.conn.connectionId))
  51. {
  52. Debug.Log(AllPlayers[msg.conn.connectionId].Name + "has disconnected.");
  53. AllPlayers.Remove(msg.conn.connectionId);
  54. }
  55. else
  56. Debug.Log("Unkown player has disconnected.");
  57. }
  58. }
  59. }