Class NetworkConnection
A High level network connection. This is used for connections from client-to-server and for connection from server-to-client.
A NetworkConnection corresponds to a specific connection for a host in the transport layer. It has a connectionId that is assigned by the transport layer and passed to the Initialize function.
A NetworkClient has one NetworkConnection. A NetworkServerSimple manages multiple NetworkConnections. The NetworkServer has multiple "remote" connections and a "local" connection for the local client.
The NetworkConnection class provides message sending and handling facilities. For sending data over a network, there are methods to send message objects, byte arrays, and NetworkWriter objects. To handle data arriving from the network, handler functions can be registered for message Ids, byte arrays can be processed by HandleBytes(), and NetworkReader object can be processed by HandleReader().
NetworkConnection objects also act as observers for networked objects. When a connection is an observer of a networked object with a NetworkIdentity, then the object will be visible to corresponding client for the connection, and incremental state changes will be sent to the client.
NetworkConnection objects can "own" networked game objects. Owned objects will be destroyed on the server by default when the connection is destroyed. A connection owns the player objects created by its client, and other objects with client-authority assigned to the corresponding client.
There are many virtual functions on NetworkConnection that allow its behaviour to be customized. NetworkClient and NetworkServer can both be made to instantiate custom classes derived from NetworkConnection by setting their networkConnectionClass member variable.
Namespace: UnityEngine.Networking
Syntax
[Obsolete("The high level API classes are deprecated and will be removed in the future.")]
public class NetworkConnection : IDisposable
Constructors
NetworkConnection()
Declaration
public NetworkConnection()
Fields
address
The IP address associated with the connection.
Declaration
public string address
Field Value
Type | Description |
---|---|
String |
connectionId
Unique identifier for this connection that is assigned by the transport layer.
On a server, this Id is unique for every connection on the server. On a client this Id is local to the client, it is not the same as the Id on the server for this connection.
Transport layers connections begin at one. So on a client with a single connection to a server, the connectionId of that connection will be one. In NetworkServer, the connectionId of the local connection is zero.
Clients do not know their connectionId on the server, and do not know the connectionId of other clients on the server.
Declaration
public int connectionId
Field Value
Type | Description |
---|---|
Int32 |
hostId
Transport level host ID for this connection.
This is assigned by the transport layer and passed to the connection instance through the Initialize function.
Declaration
public int hostId
Field Value
Type | Description |
---|---|
Int32 |
isReady
Flag that tells if the connection has been marked as "ready" by a client calling ClientScene.Ready().
This property is read-only. It is set by the system on the client when ClientScene.Ready() is called, and set by the system on the server when a ready message is received from a client.
A client that is ready is sent spawned objects by the server and updates to the state of spawned objects. A client that is not ready is not sent spawned objects.
Declaration
public bool isReady
Field Value
Type | Description |
---|---|
Boolean |
lastMessageTime
The last time that a message was received on this connection.
This includes internal system messages (such as Commands and ClientRpc calls) and user messages.
Declaration
public float lastMessageTime
Field Value
Type | Description |
---|---|
Single |
logNetworkMessages
Setting this to true will log the contents of network message to the console.
Warning: this can be a lot of data and can be very slow. Both incoming and outgoing messages are logged. The format of the logs is:
ConnectionSend con:1 bytes:11 msgId:5 FB59D743FD120000000000 ConnectionRecv con:1 bytes:27 msgId:8 14F21000000000016800AC3FE090C240437846403CDDC0BD3B0000
Note that these are application-level network messages, not protocol-level packets. There will typically be multiple network messages combined in a single protocol packet.
Declaration
public bool logNetworkMessages
Field Value
Type | Description |
---|---|
Boolean |
Properties
clientOwnedObjects
A list of the NetworkIdentity objects owned by this connection.
This includes the player object for the connection - if it has localPlayerAutority set, and any objects spawned with local authority or set with AssignLocalAuthority. This list is read only.
This list can be used to validate messages from clients, to ensure that clients are only trying to control objects that they own.
using UnityEngine;
using UnityEngine.Networking;
public class Handler
{
static public void HandleTransform(NetworkMessage netMsg)
{
NetworkInstanceId netId = netMsg.reader.ReadNetworkId();
GameObject foundObj = NetworkServer.FindLocalObject(netId);
if (foundObj == null)
{
return;
}
NetworkTransform foundSync = foundObj.GetComponent<NetworkTransform>();
if (foundSync == null)
{
return;
}
if (!foundSync.localPlayerAuthority)
{
return;
}
if (netMsg.conn.clientOwnedObjects.Contains(netId))
{
// process message
}
else
{
// error
}
}
}
Declaration
public HashSet<NetworkInstanceId> clientOwnedObjects { get; }
Property Value
Type | Description |
---|---|
HashSet<NetworkInstanceId> |
isConnected
True if the connection is connected to a remote end-point.
This applies to NetworkServer and NetworkClient connections. When not connected, the hostID will be -1. When connected, the hostID will be a positive integer.
Declaration
public bool isConnected { get; }
Property Value
Type | Description |
---|---|
Boolean |
lastError
The last error associated with this connection.
Retrieve the last error that occurred on the connection, this value is set every time an event is received from the NetworkTransport.
In the following example, OnServerDisconnect is overridden from NetworkManager:
using UnityEngine;
using UnityEngine.Networking;
public class ExampleScript : NetworkManager
{
public override void OnServerDisconnect(NetworkConnection conn)
{
if (conn.lastError != NetworkError.Ok)
{
if (LogFilter.logError)
{
Debug.LogError("ServerDisconnected due to error: " + conn.lastError);
}
}
}
}
Declaration
public NetworkError lastError { get; }
Property Value
Type | Description |
---|---|
NetworkError |
playerControllers
The list of players for this connection.
In most cases this will be a single player. But, for "Couch Multiplayer" there could be multiple players for a single client. To see the players on your own client see ClientScene.localPlayers list.
Declaration
public List<PlayerController> playerControllers { get; }
Property Value
Type | Description |
---|---|
List<PlayerController> |
Methods
CheckHandler(Int16)
This function checks if there is a message handler registered for the message ID.
This is usually not required, as InvokeHandler handles message IDs without handlers.
Declaration
public bool CheckHandler(short msgType)
Parameters
Type | Name | Description |
---|---|---|
Int16 | msgType | The message ID of the handler to look for. |
Returns
Type | Description |
---|---|
Boolean | True if a handler function was found. |
Disconnect()
Disconnects this connection.
Declaration
public void Disconnect()
Dispose()
Disposes of this connection, releasing channel buffers that it holds.
Declaration
public void Dispose()
Dispose(Boolean)
Declaration
protected virtual void Dispose(bool disposing)
Parameters
Type | Name | Description |
---|---|---|
Boolean | disposing |
Finalize()
Declaration
protected void Finalize()
FlushChannels()
This causes the channels of the network connection to flush their data to the transport layer.
This is called automatically by connections used by NetworkServer and NetworkClient, but can be called manually for connections used in other contexts.
Declaration
public void FlushChannels()
GetStatsIn(out Int32, out Int32)
Get statistics for incoming traffic.
Declaration
public virtual void GetStatsIn(out int numMsgs, out int numBytes)
Parameters
Type | Name | Description |
---|---|---|
Int32 | numMsgs | Number of messages received. |
Int32 | numBytes | Number of bytes received. |
GetStatsOut(out Int32, out Int32, out Int32, out Int32)
Get statistics for outgoing traffic.
Declaration
public virtual void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond)
Parameters
Type | Name | Description |
---|---|---|
Int32 | numMsgs | Number of messages sent. |
Int32 | numBufferedMsgs | Number of messages currently buffered for sending. |
Int32 | numBytes | Number of bytes sent. |
Int32 | lastBufferedPerSecond | How many messages were buffered in the last second. |
HandleBytes(Byte[], Int32, Int32)
This makes the connection process the data contained in the buffer, and call handler functions.
The data is assumed to have come from the network, and contains network messages.
This function is used by network connections when they receive data.
Declaration
protected void HandleBytes(byte[] buffer, int receivedSize, int channelId)
Parameters
Type | Name | Description |
---|---|---|
Byte[] | buffer | Data to process. |
Int32 | receivedSize | Size of the data to process. |
Int32 | channelId | Channel the data was recieved on. |
HandleReader(NetworkReader, Int32, Int32)
This makes the connection process the data contained in the stream, and call handler functions.
The data in the stream is assumed to have come from the network, and contains network messages.
This function is used by network connections when they receive data.
Declaration
protected void HandleReader(NetworkReader reader, int receivedSize, int channelId)
Parameters
Type | Name | Description |
---|---|---|
NetworkReader | reader | Stream that contains data. |
Int32 | receivedSize | Size of the data. |
Int32 | channelId | Channel the data was received on. |
Initialize(String, Int32, Int32, HostTopology)
This inializes the internal data structures of a NetworkConnection object, including channel buffers.
This is called by NetworkServer and NetworkClient on connection objects, but if used outside of that context, this function should be called before the connection is used.
This function can be overriden to perform additional initialization for the connection, but the base class Initialize function should always be called as it is required to setup internal state.
Declaration
public virtual void Initialize(string networkAddress, int networkHostId, int networkConnectionId, HostTopology hostTopology)
Parameters
Type | Name | Description |
---|---|---|
String | networkAddress | The host or IP connected to. |
Int32 | networkHostId | The transport hostId for the connection. |
Int32 | networkConnectionId | The transport connectionId for the connection. |
HostTopology | hostTopology | The topology to be used. |
InvokeHandler(Int16, NetworkReader, Int32)
This function invokes the registered handler function for a message.
Network connections used by the NetworkClient and NetworkServer use this function for handling network messages.
Declaration
public bool InvokeHandler(short msgType, NetworkReader reader, int channelId)
Parameters
Type | Name | Description |
---|---|---|
Int16 | msgType | The message type of the handler to use. |
NetworkReader | reader | The stream to read the contents of the message from. |
Int32 | channelId | The channel that the message arrived on. |
Returns
Type | Description |
---|---|
Boolean | True if a handler function was found and invoked. |
InvokeHandler(NetworkMessage)
This function invokes the registered handler function for a message.
Network connections used by the NetworkClient and NetworkServer use this function for handling network messages.
Declaration
public bool InvokeHandler(NetworkMessage netMsg)
Parameters
Type | Name | Description |
---|---|---|
NetworkMessage | netMsg | The message object to process. |
Returns
Type | Description |
---|---|
Boolean | True if a handler function was found and invoked. |
InvokeHandlerNoData(Int16)
This function invokes the registered handler function for a message, without any message data.
This is useful to invoke handlers that dont have any additional data, such as the handlers for MsgType.Connect.
Declaration
public bool InvokeHandlerNoData(short msgType)
Parameters
Type | Name | Description |
---|---|---|
Int16 | msgType | The message ID of the handler to invoke. |
Returns
Type | Description |
---|---|
Boolean | True if a handler function was found and invoked. |
RegisterHandler(Int16, NetworkMessageDelegate)
This registers a handler function for a message Id.
Declaration
public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
Parameters
Type | Name | Description |
---|---|---|
Int16 | msgType | The message ID to register. |
NetworkMessageDelegate | handler | The handler function to register. |
ResetStats()
Resets the statistics that are returned from NetworkClient.GetConnectionStats().
Declaration
public void ResetStats()
Send(Int16, MessageBase)
This sends a network message with a message ID on the connection. This message is sent on channel zero, which by default is the reliable channel.
Declaration
public virtual bool Send(short msgType, MessageBase msg)
Parameters
Type | Name | Description |
---|---|---|
Int16 | msgType | The ID of the message to send. |
MessageBase | msg | The message to send. |
Returns
Type | Description |
---|---|
Boolean | True if the message was sent. |
SendByChannel(Int16, MessageBase, Int32)
This sends a network message on the connection using a specific transport layer channel.
Declaration
public virtual bool SendByChannel(short msgType, MessageBase msg, int channelId)
Parameters
Type | Name | Description |
---|---|---|
Int16 | msgType | The message ID to send. |
MessageBase | msg | The message to send. |
Int32 | channelId | The transport layer channel to send on. |
Returns
Type | Description |
---|---|
Boolean | True if the message was sent. |
SendBytes(Byte[], Int32, Int32)
This sends an array of bytes on the connection.
Declaration
public virtual bool SendBytes(byte[] bytes, int numBytes, int channelId)
Parameters
Type | Name | Description |
---|---|---|
Byte[] | bytes | The array of data to be sent. |
Int32 | numBytes | The number of bytes in the array to be sent. |
Int32 | channelId | The transport channel to send on. |
Returns
Type | Description |
---|---|
Boolean | Success if data was sent. |
SendUnreliable(Int16, MessageBase)
This sends a network message with a message ID on the connection. This message is sent on channel one, which by default is the unreliable channel.
Declaration
public virtual 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 a NetworkWriter object on the connection.
The example below constructs a writer and sends it on a connection.
using UnityEngine;
using UnityEngine.Networking;
public class ExampleScript : MonoBehaviour
{
public bool Send(short msgType, MessageBase msg, NetworkConnection conn)
{
NetworkWriter writer = new NetworkWriter();
writer.StartMessage(msgType);
msg.Serialize(writer);
writer.FinishMessage();
return conn.SendWriter(writer, Channels.DefaultReliable);
}
}
Declaration
public virtual bool SendWriter(NetworkWriter writer, int channelId)
Parameters
Type | Name | Description |
---|---|---|
NetworkWriter | writer | A writer object containing data to send. |
Int32 | channelId | The transport channel to send on. |
Returns
Type | Description |
---|---|
Boolean | True if the data was sent. |
SetChannelOption(Int32, ChannelOption, Int32)
This sets an option on the network channel.
Channel options are usually advanced tuning parameters.
Declaration
public bool SetChannelOption(int channelId, ChannelOption option, int value)
Parameters
Type | Name | Description |
---|---|---|
Int32 | channelId | The channel the option will be set on. |
ChannelOption | option | The option to set. |
Int32 | value | The value for the option. |
Returns
Type | Description |
---|---|
Boolean | True if the option was set. |
SetMaxDelay(Single)
The maximum time in seconds that messages are buffered before being sent.
If this is set to zero, then there will be no buffering of messages before they are sent to the transport layer. This may reduce latency but can lead to packet queue overflow issues if many small packets are being sent.
Declaration
public void SetMaxDelay(float seconds)
Parameters
Type | Name | Description |
---|---|---|
Single | seconds | Time in seconds. |
ToString()
Returns a string representation of the NetworkConnection object state.
Declaration
public override string ToString()
Returns
Type | Description |
---|---|
String |
Overrides
TransportReceive(Byte[], Int32, Int32)
This virtual function allows custom network connection classes to process data from the network before it is passed to the application.
The default implementation of this function calls HandleBytes() on the received data. Custom implmentations can also use HandleBytes(), but can pass modified versions of the data received or other data.
This example logs the data received to the console, then passes it to HandleBytes.
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.Text;
public class DebugConnection : NetworkConnection
{
public override void TransportReceive(byte[] bytes, int numBytes, int channelId)
{
StringBuilder msg = new StringBuilder();
for (int i = 0; i < numBytes; i++) {
{
var s = String.Format("{0:X2}", bytes[i]);
msg.Append(s);
if (i > 50) break;
}
UnityEngine.Debug.LogError("TransportReceive h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg);
HandleBytes(bytes, numBytes, channelId);
}
}
Other uses for this function could be data compression or data encryption.
Custom network connection classes are used by setting NetworkServer.NetworkConnectionClass and NetworkClient.NetworkConnectionClass.
using UnityEngine;
using UnityEngine.Networking;
public class SpaceManager : NetworkManager
{
void Start()
{
NetworkServer.networkConnectionClass = typeof(DebugConnection);
NetworkClient.networkConnectionClass = typeof(DebugConnection);
}
}
Declaration
public virtual void TransportReceive(byte[] bytes, int numBytes, int channelId)
Parameters
Type | Name | Description |
---|---|---|
Byte[] | bytes | The data recieved. |
Int32 | numBytes | The size of the data recieved. |
Int32 | channelId | The channel that the data was received on. |
TransportRecieve(Byte[], Int32, Int32)
Declaration
[Obsolete("TransportRecieve has been deprecated. Use TransportReceive instead.", false)]
public virtual void TransportRecieve(byte[] bytes, int numBytes, int channelId)
Parameters
Type | Name | Description |
---|---|---|
Byte[] | bytes | |
Int32 | numBytes | |
Int32 | channelId |
TransportSend(Byte[], Int32, Int32, out Byte)
This virtual function allows custom network connection classes to process data send by the application before it goes to the network transport layer.
The default implementation of this function calls NetworkTransport.Send() with the supplied data, but custom implementations can pass modified versions of the data. This example logs the sent data to the console:
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.Text;
class DebugConnection : NetworkConnection
{
public override bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error)
{
StringBuilder msg = new StringBuilder();
for (int i = 0; i < numBytes; i++)
{
var s = String.Format("{0:X2}", bytes[i]);
msg.Append(s);
if (i > 50) break;
}
UnityEngine.Debug.LogError("TransportSend h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg);
return NetworkTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error);
}
}
Other uses for this function could be data compression or data encryption.
Custom network connection classes are used by setting NetworkServer.NetworkConnectionClass and NetworkClient.NetworkConnectionClass.
using UnityEngine;
using UnityEngine.Networking;
public class SpaceManager : NetworkManager
{
void Start()
{
NetworkServer.networkConnectionClass = typeof(DebugConnection);
NetworkClient.networkConnectionClass = typeof(DebugConnection);
}
}
Declaration
public virtual bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error)
Parameters
Type | Name | Description |
---|---|---|
Byte[] | bytes | Data to send. |
Int32 | numBytes | Size of data to send. |
Int32 | channelId | Channel to send data on. |
Byte | error | Error code for send. |
Returns
Type | Description |
---|---|
Boolean | True if data was sent. |
UnregisterHandler(Int16)
This removes the handler registered for a message Id.
Declaration
public void UnregisterHandler(short msgType)
Parameters
Type | Name | Description |
---|---|---|
Int16 | msgType | The message ID to unregister. |