Class NetworkClient | Multiplayer HLAPI | 1.0.8
docs.unity3d.com
    Show / Hide Table of Contents

    Class NetworkClient

    This is a network client class used by the networking system. It contains a NetworkConnection that is used to connect to a network server.

    The NetworkClient handle connection state, messages handlers, and connection configuration. There can be many NetworkClient instances in a process at a time, but only one that is connected to a game server (NetworkServer) that uses spawned objects.

    NetworkClient has an internal update function where it handles events from the transport layer. This includes asynchronous connect events, disconnect events and incoming data from a server.

    The NetworkManager has a NetworkClient instance that it uses for games that it starts, but the NetworkClient may be used by itself.

    Inheritance
    Object
    NetworkClient
    Namespace: UnityEngine.Networking
    Syntax
    [Obsolete("The high level API classes are deprecated and will be removed in the future.")]
    public class NetworkClient

    Constructors

    NetworkClient()

    Creates a new NetworkClient instance.

    Declaration
    public NetworkClient()

    NetworkClient(NetworkConnection)

    Declaration
    public NetworkClient(NetworkConnection conn)
    Parameters
    Type Name Description
    NetworkConnection conn

    Fields

    m_AsyncConnect

    Declaration
    protected NetworkClient.ConnectState m_AsyncConnect
    Field Value
    Type Description
    NetworkClient.ConnectState

    m_Connection

    Declaration
    protected NetworkConnection m_Connection
    Field Value
    Type Description
    NetworkConnection

    Properties

    active

    True if a network client is currently active.

    Declaration
    public static bool active { get; }
    Property Value
    Type Description
    Boolean

    allClients

    A list of all the active network clients in the current process.

    This is NOT a list of all clients that are connected to the remote server, it is client instances on the local game.

    Declaration
    public static List<NetworkClient> allClients { get; }
    Property Value
    Type Description
    List<NetworkClient>

    connection

    The NetworkConnection object this client is using.

    Declaration
    public NetworkConnection connection { get; }
    Property Value
    Type Description
    NetworkConnection

    handlers

    The registered network message handlers.

    Declaration
    public Dictionary<short, NetworkMessageDelegate> handlers { get; }
    Property Value
    Type Description
    Dictionary<Int16, NetworkMessageDelegate>

    hostPort

    The local port that the network client uses to connect to the server.

    It defaults to 0, which means the network client will use a free port of system choice.

    Declaration
    public int hostPort { get; set; }
    Property Value
    Type Description
    Int32

    hostTopology

    The host topology that this client is using.

    This is read-only once the client is started.

    Declaration
    public HostTopology hostTopology { get; }
    Property Value
    Type Description
    HostTopology

    isConnected

    This gives the current connection status of the client.

    Declaration
    public bool isConnected { get; }
    Property Value
    Type Description
    Boolean

    networkConnectionClass

    The class to use when creating new NetworkConnections.

    This can be set with SetNetworkConnectionClass. This allows custom classes that do special processing of data from the transport layer to be used with the NetworkClient.

    See NetworkConnection.TransportSend and NetworkConnection.TransportReceive for details.

    Declaration
    public Type networkConnectionClass { get; }
    Property Value
    Type Description
    Type

    numChannels

    The number of QoS channels currently configured for this client.

    Declaration
    public int numChannels { get; }
    Property Value
    Type Description
    Int32

    peers

    Declaration
    [Obsolete("Moved to NetworkMigrationManager.")]
    public PeerInfoMessage[] peers { get; }
    Property Value
    Type Description
    PeerInfoMessage[]

    serverIp

    The IP address of the server that this client is connected to.

    This will be empty if the client has not connected yet.

    Declaration
    public string serverIp { get; }
    Property Value
    Type Description
    String

    serverPort

    The port of the server that this client is connected to.

    This will be zero if the client has not connected yet.

    Declaration
    public int serverPort { get; }
    Property Value
    Type Description
    Int32

    Methods

    Configure(ConnectionConfig, Int32)

    This configures the transport layer settings for a client.

    The settings in the ConnectionConfig or HostTopology object will be used to configure the transport layer connection used by this client. This must match the configuration of the server.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class Example : MonoBehaviour
    {
       void DoConnect()
       {
           ConnectionConfig config = new ConnectionConfig();
           config.AddChannel(QosType.ReliableSequenced);
           config.AddChannel(QosType.UnreliableSequenced);
           config.PacketSize = 500;
           NetworkClient client = new NetworkClient();
           client.Configure(config, 1);
           client.Connect("127.0.0.1", 7070);
       }
    };
    Declaration
    public bool Configure(ConnectionConfig config, int maxConnections)
    Parameters
    Type Name Description
    ConnectionConfig config

    Transport layer configuration object.

    Int32 maxConnections

    The maximum number of connections to allow.

    Returns
    Type Description
    Boolean

    True if the configuration was successful.

    Configure(HostTopology)

    This configures the transport layer settings for a client.

    The settings in the ConnectionConfig or HostTopology object will be used to configure the transport layer connection used by this client. This must match the configuration of the server.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class Example : MonoBehaviour
    {
       void DoConnect()
       {
           ConnectionConfig config = new ConnectionConfig();
           config.AddChannel(QosType.ReliableSequenced);
           config.AddChannel(QosType.UnreliableSequenced);
           config.PacketSize = 500;
           NetworkClient client = new NetworkClient();
           client.Configure(config, 1);
           client.Connect("127.0.0.1", 7070);
       }
    };
    Declaration
    public bool Configure(HostTopology topology)
    Parameters
    Type Name Description
    HostTopology topology

    Transport layer topology object.

    Returns
    Type Description
    Boolean

    True if the configuration was successful.

    Connect(EndPoint)

    Declaration
    public void Connect(EndPoint secureTunnelEndPoint)
    Parameters
    Type Name Description
    EndPoint secureTunnelEndPoint

    Connect(String, Int32)

    Connect client to a NetworkServer instance.

    Connecting to a server is asynchronous. There is connection message that is fired when the client connects. If the connection fails, a MsgType.Error message will be generated. Once a connection is established you are able to send messages on the connection using NetworkClient.Send(). If using other features of the high level api, the client should call NetworkClient.IsReady() once it is ready to participate in the game. At that point the client will be sent spawned objects and state update messages.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class NetClient
    {
       NetworkClient myClient;
    
       public void OnConnected(NetworkConnection conn, NetworkReader reader)
       {
           Debug.Log("Connected to server");
       }
    
       public void OnDisconnected(NetworkConnection conn, NetworkReader reader)
       {
           Debug.Log("Disconnected from server");
       }
    
       public void OnError(NetworkConnection conn, NetworkReader reader)
       {
           SystemErrorMessage errorMsg = reader.SmartRead<SystemErrorMessage>();
           Debug.Log("Error connecting with code " + errorMsg.errorCode);
       }
    
       public void Start()
       {
           myClient = NetworkClient.Instance;
           myClient.RegisterHandler(MsgType.SYSTEM_CONNECT, OnConnected);
           myClient.RegisterHandler(MsgType.SYSTEM_DISCONNECT, OnDisconnected);
           myClient.RegisterHandler(MsgType.SYSTEM_ERROR, OnError);
           myClient.Connect("127.0.0.1", 8888);
       }
    }
    Declaration
    public void Connect(string serverIp, int serverPort)
    Parameters
    Type Name Description
    String serverIp

    Target IP address or hostname.

    Int32 serverPort

    Target port number.

    Connect(MatchInfo)

    Declaration
    public void Connect(MatchInfo matchInfo)
    Parameters
    Type Name Description
    MatchInfo matchInfo

    ConnectWithSimulator(String, Int32, Int32, Single)

    Connect client to a NetworkServer instance with simulated latency and packet loss.

    Declaration
    public void ConnectWithSimulator(string serverIp, int serverPort, int latency, float packetLoss)
    Parameters
    Type Name Description
    String serverIp

    Target IP address or hostname.

    Int32 serverPort

    Target port number.

    Int32 latency

    Simulated latency in milliseconds.

    Single packetLoss

    Simulated packet loss percentage.

    Disconnect()

    Disconnect from server.

    The disconnect message will be invoked.

    Declaration
    public virtual void Disconnect()

    GetConnectionStats()

    Retrieves statistics about the network packets sent on this connection.

    Declaration
    public Dictionary<short, NetworkConnection.PacketStat> GetConnectionStats()
    Returns
    Type Description
    Dictionary<Int16, NetworkConnection.PacketStat>

    Dictionary of packet statistics for the client's connection.

    GetRTT()

    Gets the Return Trip Time for this connection.

    This value is calculated by the transport layer.

    Declaration
    public int GetRTT()
    Returns
    Type Description
    Int32

    Return trip time in milliseconds.

    GetStatsIn(out Int32, out Int32)

    Get inbound network statistics for the client.

    Declaration
    public void GetStatsIn(out int numMsgs, out int numBytes)
    Parameters
    Type Name Description
    Int32 numMsgs

    Number of messages received so far.

    Int32 numBytes

    Number of bytes received so far.

    GetStatsOut(out Int32, out Int32, out Int32, out Int32)

    Get outbound network statistics for the client.

    Declaration
    public void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond)
    Parameters
    Type Name Description
    Int32 numMsgs

    Number of messages sent so far (including collated messages send through buffer).

    Int32 numBufferedMsgs

    Number of messages sent through buffer.

    Int32 numBytes

    Number of bytes sent so far.

    Int32 lastBufferedPerSecond

    Number of messages buffered for sending per second.

    GetTotalConnectionStats()

    Retrieves statistics about the network packets sent on all connections.

    Declaration
    public static Dictionary<short, NetworkConnection.PacketStat> GetTotalConnectionStats()
    Returns
    Type Description
    Dictionary<Int16, NetworkConnection.PacketStat>

    Dictionary of stats.

    ReconnectToNewHost(EndPoint)

    Declaration
    public bool ReconnectToNewHost(EndPoint secureTunnelEndPoint)
    Parameters
    Type Name Description
    EndPoint secureTunnelEndPoint
    Returns
    Type Description
    Boolean

    ReconnectToNewHost(String, Int32)

    This is used by a client that has lost the connection to the old host, to reconnect to the new host of a game.

    Declaration
    public bool ReconnectToNewHost(string serverIp, int serverPort)
    Parameters
    Type Name Description
    String serverIp

    The IP address of the new host.

    Int32 serverPort

    The port of the new host.

    Returns
    Type Description
    Boolean

    True if able to reconnect.

    RegisterHandler(Int16, NetworkMessageDelegate)

    Register a handler for a particular message type.

    There are several system message types which you can add handlers for. You can also add your own message types.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class Server : MonoBehaviour
    {
       void Start()
       {
           NetworkServer.Listen(7070);
           Debug.Log("Registering server callbacks");
           NetworkClient client = new NetworkClient();
           client.RegisterHandler(MsgType.Connect, OnConnected);
       }
    
       void OnConnected(NetworkMessage netMsg)
       {
           Debug.Log("Client connected");
       }
    }
    Declaration
    public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
    Parameters
    Type Name Description
    Int16 msgType

    Message type number.

    NetworkMessageDelegate handler

    Function handler which will be invoked for when this message type is received.

    RegisterHandlerSafe(Int16, NetworkMessageDelegate)

    Declaration
    public void RegisterHandlerSafe(short msgType, NetworkMessageDelegate handler)
    Parameters
    Type Name Description
    Int16 msgType
    NetworkMessageDelegate handler

    ResetConnectionStats()

    Resets the statistics return by NetworkClient.GetConnectionStats() to zero values.

    Useful when building per-second network statistics.

    Declaration
    public void ResetConnectionStats()

    Send(Int16, MessageBase)

    This sends a network message with a message Id to the server. This message is sent on channel zero, which by default is the reliable channel.

    The message must be an instance of a class derived from MessageBase.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class RegisterHostMessage : MessageBase
    {
       public string gameName;
       public string comment;
       public bool passwordProtected;
    }
    
    public class MasterClient
    {
       public NetworkClient client;
    
       public const short RegisterHostMsgId = 888;
    
       public void RegisterHost(string name)
       {
           RegisterHostMessage msg = new RegisterHostMessage();
           msg.gameName = name;
           msg.comment = "test";
           msg.passwordProtected = false;
           client.Send(RegisterHostMsgId, msg);
       }
    }

    The message id passed to Send() is used to identify the handler function to invoke on the server when the message is received.

    Declaration
    public bool Send(short msgType, MessageBase msg)
    Parameters
    Type Name Description
    Int16 msgType

    The id of the message to send.

    MessageBase msg

    A message instance to send.

    Returns
    Type Description
    Boolean

    True if message was sent.

    SendByChannel(Int16, MessageBase, Int32)

    This sends a network message with a message Id to the server on a specific channel.

    This does the same thing as NetworkClient.Send(), but allows a transport layer QoS channel to be specified.

    Declaration
    public bool SendByChannel(short msgType, MessageBase msg, int channelId)
    Parameters
    Type Name Description
    Int16 msgType

    The id of the message to send.

    MessageBase msg

    The message to send.

    Int32 channelId

    The channel to send the message on.

    Returns
    Type Description
    Boolean

    True if the message was sent.

    SendBytes(Byte[], Int32, Int32)

    This sends the data in an array of bytes to the server that the client is connected to.

    The data must be properly formatted.

    Declaration
    public bool SendBytes(byte[] data, int numBytes, int channelId)
    Parameters
    Type Name Description
    Byte[] data

    Data to send.

    Int32 numBytes

    Number of bytes of data.

    Int32 channelId

    The QoS channel to send data on.

    Returns
    Type Description
    Boolean

    True if successfully sent.

    SendUnreliable(Int16, MessageBase)

    This sends a network message with a message Id to the server on channel one, which by default is the unreliable channel.

    This does the same thing as NetworkClient.Send(), except that it send on the unreliable channel.

    Declaration
    public bool SendUnreliable(short msgType, MessageBase msg)
    Parameters
    Type Name Description
    Int16 msgType

    The message id to send.

    MessageBase msg

    The message to send.

    Returns
    Type Description
    Boolean

    True if the message was sent.

    SendWriter(NetworkWriter, Int32)

    This sends the contents of the NetworkWriter's buffer to the connected server on the specified channel.

    The format of the data in the writer must be properly formatted for it to be processed as a message by the server. The functions StartMessage() and FinishMessage() can be used to properly format messages:

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class TestClient
    {
       public NetworkClient client;
    
       public const int RegisterHostMsgId = 888;
    
       public void RegisterHost(string name)
       {
           NetworkWriter writer = new NetworkWriter();
           writer.StartMessage(RegisterHostMsgId);
           writer.Write(name);
           writer.FinishMessage();
           client.SendWriter(writer, Channels.DefaultReliable);
       }
    }
    Declaration
    public bool SendWriter(NetworkWriter writer, int channelId)
    Parameters
    Type Name Description
    NetworkWriter writer

    Writer object containing data to send.

    Int32 channelId

    QoS channel to send data on.

    Returns
    Type Description
    Boolean

    True if data successfully sent.

    SetMaxDelay(Single)

    Set the maximum amount of time that can pass for transmitting the send buffer.

    Declaration
    public void SetMaxDelay(float seconds)
    Parameters
    Type Name Description
    Single seconds

    Delay in seconds.

    SetNetworkConnectionClass<T>()

    This sets the class that is used when creating new network connections.

    The class must be derived from NetworkConnection.

    Declaration
    public void SetNetworkConnectionClass<T>()
        where T : NetworkConnection
    Type Parameters
    Name Description
    T

    Shutdown()

    Shut down a client.

    This should be done when a client is no longer going to be used.

    Declaration
    public void Shutdown()

    ShutdownAll()

    Shuts down all network clients.

    This also shuts down the transport layer.

    Declaration
    public static void ShutdownAll()

    UnregisterHandler(Int16)

    Unregisters a network message handler.

    Declaration
    public void UnregisterHandler(short msgType)
    Parameters
    Type Name Description
    Int16 msgType

    The message type to unregister.

    Back to top
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023