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.

66 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 LoginManager
  8. {
  9. private ServerManager ServerManager;
  10. public LoginManager(ServerManager ServerManager)
  11. {
  12. this.ServerManager = ServerManager;
  13. RegisterHandles();
  14. }
  15. public void RegisterHandles()
  16. {
  17. ServerManager.Server.RegisterHandler(LoginMsgID.Name, OnPlayerLogin);
  18. ServerManager.Server.RegisterHandler(MsgType.Connect, OnConnect);
  19. ServerManager.Server.RegisterHandler(MsgType.Disconnect, OnDisconnect);
  20. }
  21. //Called when a player logs in
  22. public void OnPlayerLogin(NetworkMessage msg)
  23. {
  24. StringMsg stringMsg;
  25. if (!Utility.ReadMessage<StringMsg>(msg, out stringMsg))
  26. return;
  27. Debug.Log("Player login: " + stringMsg.String);
  28. if (ServerManager.AllPlayers.ContainsKey(stringMsg.ID))
  29. {
  30. Debug.Log(stringMsg.String + " already logged in");
  31. return;
  32. }
  33. Player newPlayer = new Player(msg.conn, stringMsg.String);
  34. ServerManager.AllPlayers.Add(newPlayer.ID, newPlayer);
  35. }
  36. private void OnConnect(NetworkMessage msg)
  37. {
  38. Debug.Log("New Connection: \n Address: " + msg.conn.address + "\n ID: " + msg.conn.connectionId);
  39. msg.conn.Send(LoginMsgID.QueryName, new PlayerMsg((byte)msg.conn.connectionId));
  40. }
  41. private void OnDisconnect(NetworkMessage msg)
  42. {
  43. if (ServerManager.AllPlayers.ContainsKey(msg.conn.connectionId))
  44. {
  45. Debug.Log(ServerManager.AllPlayers[msg.conn.connectionId].Name + "has disconnected.");
  46. ServerManager.AllPlayers.Remove(msg.conn.connectionId);
  47. }
  48. else
  49. Debug.Log("Unkown player has disconnected.");
  50. }
  51. }
  52. }