Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Question Cannot connect Client

Discussion in 'Unity Transport' started by Xa456789, Feb 4, 2024.

  1. Xa456789

    Xa456789

    Joined:
    Aug 5, 2022
    Posts:
    21
    I have created a Client and Server Script following the manual and a tutorial. When just attaching the scripts to objects everything works fine, but when making the unity editor a host (by creating server as well as client) and opening a build doing the same but this time only a client, it just doesn't connect. I'm using the LoopbackIpv4 address (localhost).
    Here is my Code:
    BaseClient.cs
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Unity.Networking.Transport;
    5. using Unity.Collections;
    6.  
    7. public class BaseClient : MonoBehaviour
    8. {
    9.     public NetworkDriver driver;
    10.     protected NetworkConnection serverConnection;
    11.  
    12.     private string ipAddr = "127.0.0.1";
    13.     private ushort port = 44444;
    14.  
    15.     public ushort GetPort() { return port; }
    16.  
    17.     public void SetPort(ushort port) { this.port = port; }
    18.  
    19.     public string GetIpAddr() { return ipAddr; }
    20.     public void SetIpAddr(string IpAddr) { this.ipAddr = IpAddr; }
    21.  
    22. #if UNITY_EDITOR
    23.     private void Start() { Init(); }
    24.     private void Update() { UpdateServer(); }
    25.     private void OnDestroy() { Shutdown(); }
    26. #endif
    27.  
    28.     public virtual void Init()
    29.     {
    30.         driver = NetworkDriver.Create();
    31.         serverConnection = default;
    32.  
    33.         NetworkEndpoint endPoint = NetworkEndpoint.LoopbackIpv4.WithPort(44444);
    34.  
    35.         serverConnection = driver.Connect(endPoint);
    36.     }
    37.  
    38.     public virtual void Shutdown()
    39.     {
    40.         driver.Dispose();
    41.     }
    42.  
    43.     public virtual void UpdateServer()
    44.     {
    45.         driver.ScheduleUpdate().Complete();
    46.         UpdateMessagePump();
    47.         IsConnectionActive();
    48.     }
    49.  
    50.     private void IsConnectionActive()
    51.     {
    52.         if (!serverConnection.IsCreated)
    53.         {
    54.             Debug.Log("Lost connection");
    55.         }
    56.     }
    57.  
    58.     protected virtual void UpdateMessagePump()
    59.     {
    60.         DataStreamReader stream;
    61.        
    62.         NetworkEvent.Type cmd;
    63.  
    64.         while ((cmd = serverConnection.PopEvent(driver, out stream)) != NetworkEvent.Type.Empty)
    65.         {
    66.             if (cmd == NetworkEvent.Type.Connect)
    67.             {
    68.                 Debug.Log("Client connected to server");
    69.             }
    70.             else if (cmd == NetworkEvent.Type.Data)
    71.             {
    72.                 OnDataReceived(stream);
    73.             }
    74.             else if (cmd == NetworkEvent.Type.Disconnect)
    75.             {
    76.                 serverConnection = default(NetworkConnection);
    77.                 Debug.Log("Client disconnected");
    78.             }
    79.         }
    80.     }
    81.  
    82.     public virtual void OnDataReceived(DataStreamReader stream)
    83.     {
    84.         NetPacket packet = null;
    85.         var packetType = (PacketType)stream.ReadByte();
    86.  
    87.         packet = NetUtilities.Instance.CreatePacket(stream, packetType);
    88.  
    89.         packet.ReceivedOnClient();
    90.     }
    91.  
    92.     public virtual void SendPacketToServer(NetPacket packet)
    93.     {
    94.         DataStreamWriter writer;
    95.         driver.BeginSend(serverConnection, out writer);
    96.         packet.Serialize(ref writer);
    97.         driver.EndSend(writer);
    98.     }
    99. }
    100.  
    BaseServer.cs
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Unity.Networking.Transport;
    5. using Unity.Collections;
    6.  
    7. public class BaseServer : MonoBehaviour
    8. {
    9.     public NetworkDriver driver;
    10.     protected NativeList<NetworkConnection> connections;
    11.  
    12.     [SerializeField] private bool isOpenForNewPlayers = true;
    13.  
    14.     public bool IsOpenForNewPlayers() { return isOpenForNewPlayers; }
    15.  
    16.     public void SetIsOpenForNewPlayers(bool isOpen) { isOpenForNewPlayers = isOpen; }
    17.  
    18. #if UNITY_EDITOR
    19.     private void Start() { Init(); }
    20.     private void Update() { UpdateServer(); }
    21.     private void OnDestroy() { Shutdown(); }
    22. #endif
    23.  
    24.     public virtual void Init()
    25.     {
    26.         driver = NetworkDriver.Create();
    27.  
    28.         connections = new NativeList<NetworkConnection>(4, Allocator.Persistent);
    29.  
    30.         NetworkEndpoint endPoint = NetworkEndpoint.AnyIpv4.WithPort(44444);
    31.  
    32.         if (driver.Bind(endPoint) != 0)
    33.             Debug.Log("Could not bind to Port " + endPoint.Port);
    34.         else
    35.             driver.Listen();
    36.     }
    37.  
    38.     public virtual void Shutdown()
    39.     {
    40.         driver.Dispose();
    41.         connections.Dispose();
    42.     }
    43.  
    44.     public virtual void UpdateServer()
    45.     {
    46.         driver.ScheduleUpdate().Complete();
    47.         CleanUpConnection();
    48.         //if (IsOpenForNewPlayers())
    49.         AcceptNewConnections();
    50.         UpdateMessagePump();
    51.     }
    52.  
    53.     private void CleanUpConnection()
    54.     {
    55.         for (int i = 0; i < connections.Length; i++)
    56.         {
    57.             if (!connections[i].IsCreated)
    58.             {
    59.                 connections.RemoveAtSwapBack(i);
    60.                 i--;
    61.             }
    62.         }
    63.     }
    64.  
    65.     private void AcceptNewConnections()
    66.     {
    67.         NetworkConnection connection;
    68.  
    69.         while((connection = driver.Accept()) != default)
    70.         {
    71.             Debug.Log("Added new connection");
    72.             connections.Add(connection);
    73.         }
    74.     }
    75.  
    76.     protected virtual void UpdateMessagePump()
    77.     {
    78.         DataStreamReader stream;
    79.  
    80.         for(int i = 0; i < connections.Length; i++)
    81.         {
    82.             NetworkEvent.Type cmd;
    83.  
    84.             while ((cmd = driver.PopEventForConnection(connections[i], out stream)) != NetworkEvent.Type.Empty)
    85.             {
    86.                 if (cmd == NetworkEvent.Type.Data)
    87.                 {
    88.                     OnDataReceived(stream);
    89.                 }
    90.                 else if (cmd == NetworkEvent.Type.Disconnect)
    91.                 {
    92.                     connections[i] = default(NetworkConnection);
    93.                     Debug.Log("Client disconnect");
    94.                 }
    95.             }
    96.         }
    97.     }
    98.  
    99.     public virtual void OnDataReceived(DataStreamReader stream)
    100.     {
    101.         NetPacket packet = null;
    102.         var packetType = (PacketType)stream.ReadByte();
    103.  
    104.         packet = NetUtilities.Instance.CreatePacket(stream, packetType);
    105.  
    106.         packet.ReceivedOnServer(this);
    107.     }
    108.  
    109.     public virtual void BroadcastPacket(NetPacket packet)
    110.     {
    111.         for (int i = 0; i < connections.Length; i++)
    112.         {
    113.             if (connections[i].IsCreated)
    114.                 SendPacketToClient(connections[i], packet);
    115.         }
    116.     }
    117.  
    118.     public virtual void SendPacketToClient(NetworkConnection connection, NetPacket packet)
    119.     {
    120.         DataStreamWriter writer;
    121.         driver.BeginSend(connection, out writer);
    122.         packet.Serialize(ref writer);
    123.         driver.EndSend(writer);
    124.     }
    125. }

    I am using Unity 2022.3.18f1, Unity Transport v.2.1.0.
    Thanks in advance!
     
  2. simon-lemay-unity

    simon-lemay-unity

    Unity Technologies

    Joined:
    Jul 19, 2021
    Posts:
    441
    Based on the code you posted, your client will only start and update the driver if
    UNITY_EDITOR
    is defined. That's not the case in player builds, which would explain why your client won't connect.
     
  3. Xa456789

    Xa456789

    Joined:
    Aug 5, 2022
    Posts:
    21
    Oh ok, I was following the tutorial and didn't even listen what he said. Thanks I'm going to test it straight away!
     
  4. Xa456789

    Xa456789

    Joined:
    Aug 5, 2022
    Posts:
    21
    Works great! Thanks again!
     
  5. Xa456789

    Xa456789

    Joined:
    Aug 5, 2022
    Posts:
    21
    Quick off topic question: im trying to achive this:
    Code (CSharp):
    1. public class ClassA : BaseClass
    2. {
    3.     public int val = 1;
    4.     public int override GetValue()
    5.     {
    6.          return val;
    7.     }
    8. }
    9.  
    10. public class ClassB : BaseClass
    11. {
    12.     public bool val = true;
    13.     public bool override GetValue()
    14.     {
    15.          return val;
    16.     }
    17. }
    18.  
    19. public class BaseClass
    20. {
    21.     public virtual [RETURN TYPE] GetValue()
    22.     {
    23.        return val
    24.     }
    25. }
    I have a List with multiple BaseClasses and I want to get the Value from the subclass without needing to make one for every variable type, is this possible?
     
  6. simon-lemay-unity

    simon-lemay-unity

    Unity Technologies

    Joined:
    Jul 19, 2021
    Posts:
    441
    You'd want either an interface that specifies
    GetValue
    in that case or have
    BaseClass
    be abstract (if you don't need to instances of it). I'd suggest asking general C# questions like this on Stack Overflow, as you're likely to get more and better answers there.