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.

88 lines
2.7 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. namespace Multiplayer
  6. {
  7. public class ClientManager : MonoBehaviour
  8. {
  9. #region Inspector Variables
  10. [Header("Client Settings")]
  11. [Tooltip("Address server is hosted on")]
  12. [SerializeField]
  13. private string ServerAddress = "127.0.0.1";
  14. [Tooltip("Port to connect to server on")]
  15. [SerializeField]
  16. private int Port = 4444;
  17. [Tooltip("Connects client to server on awake")]
  18. [SerializeField]
  19. private bool ConnectOnStart = false;
  20. #endregion
  21. //Returns if client is current connected to a server
  22. public bool IsConnected { get; private set; }
  23. //UNET client class which connects to the server;
  24. private NetworkClient uNetClient;
  25. /// <summary>
  26. /// Call to connect client to host
  27. /// </summary>
  28. [ContextMenu("Start Client")]
  29. public void StartClient()
  30. {
  31. StartClient(ServerAddress, Port);
  32. }
  33. /// <summary>
  34. /// Call to connect the client to the host
  35. /// </summary>
  36. /// <param name="ServerAddress">Server Address to connect to</param>
  37. /// <param name="Port">Port to connect on</param>
  38. public void StartClient(string ServerAddress, int Port)
  39. {
  40. //If client is already connected to don't continue
  41. if (IsConnected)
  42. {
  43. Debug.Log("Client already connected to a server. Client needs to disconnect before it can connect to a server");
  44. return;
  45. }
  46. Debug.Log("Attempting to connect to: '" + ServerAddress + "' on port : '" + Port + "'");
  47. uNetClient = new NetworkClient();
  48. RegisterHandlers(uNetClient);
  49. uNetClient.Configure(ChannelConfig.DefaultTopology());
  50. uNetClient.Connect(ServerAddress, Port);
  51. }
  52. /// <summary>
  53. /// Helper function which sets up all necessary handlers for message types
  54. /// </summary>
  55. /// <param name="client"></param>
  56. private void RegisterHandlers(NetworkClient client)
  57. {
  58. client.RegisterHandler(MsgType.Connect, OnConnected);
  59. client.RegisterHandler(MsgType.Disconnect, OnDisconnected);
  60. }
  61. private void OnConnected(NetworkMessage msg)
  62. {
  63. IsConnected = true;
  64. Debug.Log("Successfully connected to server");
  65. Debug.Log("Connection ID: " + msg.conn.connectionId);
  66. }
  67. private void OnDisconnected(NetworkMessage msg)
  68. {
  69. IsConnected = false;
  70. Debug.Log("Disconnected from Server");
  71. }
  72. }
  73. }