Struct NetworkDriver
The NetworkDriver
is the main API with which users interact with the Unity Transport
package. It can be thought of as a socket with extra features. Refer to the manual for
examples of how to use this API.
Inherited Members
Namespace: Unity.Networking.Transport
Syntax
public struct NetworkDriver : IDisposable
Constructors
NetworkDriver(INetworkInterface)
Use Create(NetworkSettings) to construct NetworkDriver
instances.
Declaration
[Obsolete("Use NetworkDriver.Create(INetworkInterface networkInterface) instead.", true)]
public NetworkDriver(INetworkInterface netIf)
Parameters
Type | Name | Description |
---|---|---|
INetworkInterface | netIf |
NetworkDriver(INetworkInterface, NetworkSettings)
Use Create(NetworkSettings) to construct NetworkDriver
instances.
Declaration
[Obsolete("Use NetworkDriver.Create(INetworkInterface networkInterface, NetworkSettings settings) instead.", true)]
public NetworkDriver(INetworkInterface netIf, NetworkSettings settings)
Parameters
Type | Name | Description |
---|---|---|
INetworkInterface | netIf | |
NetworkSettings | settings |
Properties
Bound
Whether the driver has been bound to an endpoint with the Bind(NetworkEndpoint) method. Binding to an endpoint is a prerequisite to listening to new connections (with the Listen() method). It is also a prerequiste to making new connections, but the Connect(NetworkEndpoint) method will automatically bind the driver to the wildcard address if it's not already bound.
Declaration
public bool Bound { get; }
Property Value
Type | Description |
---|---|
Boolean | True if the driver is bound, false otherwise. |
CurrentSettings
Current settings used by the driver.
Declaration
public readonly NetworkSettings CurrentSettings { get; }
Property Value
Type | Description |
---|---|
NetworkSettings |
Remarks
Current settings are read-only and can't be modified except through methods like ModifySimulatorStageParameters(NetworkDriver, SimulatorUtility.Parameters).
IsCreated
Whether the driver is been correctly created.
Declaration
public readonly bool IsCreated { get; }
Property Value
Type | Description |
---|---|
Boolean | True if correctly created, false otherwise. |
Listening
Whether the driver is listening for new connections (e.g. acting like a server). Use the Listen() method to start listening for new connections.
Declaration
public bool Listening { get; }
Property Value
Type | Description |
---|---|
Boolean | True if the driver is listening, false otherwise. |
ReceiveErrorCode
Error code raised by the last receive job, if any.
Declaration
public readonly int ReceiveErrorCode { get; }
Property Value
Type | Description |
---|---|
Int32 | Code from the StatusCode enum. |
Methods
AbortSend(DataStreamWriter)
Aborts a send started with BeginSend(NetworkPipeline, NetworkConnection, out DataStreamWriter, Int32).
Declaration
public void AbortSend(DataStreamWriter writer)
Parameters
Type | Name | Description |
---|---|---|
DataStreamWriter | writer | DataStreamWriter to cancel. |
Accept()
Accept any new incoming connections. Connections must be accepted before data can be sent on them. It's also the only way to obtain the NetworkConnection value for new connections on servers.
Declaration
public NetworkConnection Accept()
Returns
Type | Description |
---|---|
NetworkConnection | New connection if any, otherwise a default-value object. |
BeginSend(NetworkConnection, out DataStreamWriter, Int32)
Begin sending data on the given connection (default pipeline).
Declaration
public int BeginSend(NetworkConnection connection, out DataStreamWriter writer, int requiredPayloadSize = 0)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | connection | Connection to send the data to. |
DataStreamWriter | writer | DataStreamWriter the data can be written to. |
Int32 | requiredPayloadSize | Size that the returned DataStreamWriter must support. The method will return an error if that payload size is not supported by the pipeline. Defaults to 0, which means the DataStreamWriter will be as large as it can be. |
Returns
Type | Description |
---|---|
Int32 | 0 on success, a negative value on error. |
BeginSend(NetworkPipeline, NetworkConnection, out DataStreamWriter, Int32)
Begin sending data on the given connection and pipeline.
Declaration
public int BeginSend(NetworkPipeline pipe, NetworkConnection connection, out DataStreamWriter writer, int requiredPayloadSize = 0)
Parameters
Type | Name | Description |
---|---|---|
NetworkPipeline | pipe | Pipeline to send the data on. |
NetworkConnection | connection | Connection to send the data to. |
DataStreamWriter | writer | DataStreamWriter the data can be written to. |
Int32 | requiredPayloadSize | Size that the returned DataStreamWriter must support. The method will return an error if that payload size is not supported by the pipeline. Defaults to 0, which means the DataStreamWriter will be as large as it can be. |
Returns
Type | Description |
---|---|
Int32 | 0 on success, a negative error code on error. |
Bind(NetworkEndpoint)
Bind the driver to an endpoint. This endpoint would normally be a local IP address and port which the driver will use for its communications. Binding to a wildcard address (AnyIpv4 or AnyIpv6) will result in the driver using any local address for its communications, and binding to port 0 will result in the driver using an ephemeral free port chosen by the OS.
Declaration
public int Bind(NetworkEndpoint endpoint)
Parameters
Type | Name | Description |
---|---|---|
NetworkEndpoint | endpoint | Endpoint to bind to. |
Returns
Type | Description |
---|---|
Int32 | 0 on success, negative error code on error. |
Exceptions
Type | Condition |
---|---|
InvalidOperationException | If the driver is not created properly, if it's already bound, or if there are already connections made to the driver (although that shouldn't be possible). Note that these exceptions are only thrown if safety checks are enabled (i.e. in the editor). |
Connect(NetworkEndpoint)
Establish a new connection to the given endpoint. Note that this only starts establishing the new connection. From there it will either succeeds (a Connect event will pop on the connection) or fail (a Disconnect event will pop on the connection) at a later time.
Declaration
public NetworkConnection Connect(NetworkEndpoint endpoint)
Parameters
Type | Name | Description |
---|---|---|
NetworkEndpoint | endpoint | Endpoint to connect to. |
Returns
Type | Description |
---|---|
NetworkConnection | New connection object, or a default-valued object on failure. |
Remarks
Establishing a new connection normally requires the driver to be bound (e.g. with the
Bind(NetworkEndpoint) method), but if that's not the case when calling this method, the
driver will be implicitly bound to the appropriate wildcard address. This is a behavior
similar to BSD sockets, where calling connect
automatically binds the socket to
an ephemeral port.
Create()
Create a new NetworkDriver
with default settings.
Declaration
public static NetworkDriver Create()
Returns
Type | Description |
---|---|
NetworkDriver | Newly-constructed driver. |
Create(NetworkSettings)
Create a new NetworkDriver
with custom settings.
Declaration
public static NetworkDriver Create(NetworkSettings settings)
Parameters
Type | Name | Description |
---|---|---|
NetworkSettings | settings | Configuration for the driver. |
Returns
Type | Description |
---|---|
NetworkDriver | Newly-constructed driver. |
Create<N>(N)
Create a new NetworkDriver
with a custom network interface.
Declaration
public static NetworkDriver Create<N>(N networkInterface)
where N : struct, INetworkInterface
Parameters
Type | Name | Description |
---|---|---|
N | networkInterface | Instance of the custom network interface. |
Returns
Type | Description |
---|---|
NetworkDriver | Newly-constructed driver. |
Type Parameters
Name | Description |
---|---|
N | Type of the network interface to use. |
Create<N>(N, NetworkSettings)
Create a new NetworkDriver
with a custom network interface and custom settings.
Declaration
public static NetworkDriver Create<N>(N networkInterface, NetworkSettings settings)
where N : struct, INetworkInterface
Parameters
Type | Name | Description |
---|---|---|
N | networkInterface | Instance of the custom network interface. |
NetworkSettings | settings | Configuration for the driver. |
Returns
Type | Description |
---|---|
NetworkDriver | Newly-constructed driver. |
Type Parameters
Name | Description |
---|---|
N | Type of the network interface to use. |
Create<N>(ref N)
Create a new NetworkDriver
with a custom network interface.
Declaration
public static NetworkDriver Create<N>(ref N networkInterface)
where N : struct, INetworkInterface
Parameters
Type | Name | Description |
---|---|---|
N | networkInterface | Instance of the custom network interface. |
Returns
Type | Description |
---|---|
NetworkDriver | Newly-constructed driver. |
Type Parameters
Name | Description |
---|---|
N | Type of the network interface to use. |
Create<N>(ref N, NetworkSettings)
Create a new NetworkDriver
with a custom network interface and custom settings.
Declaration
public static NetworkDriver Create<N>(ref N networkInterface, NetworkSettings settings)
where N : struct, INetworkInterface
Parameters
Type | Name | Description |
---|---|---|
N | networkInterface | Instance of the custom network interface. |
NetworkSettings | settings | Configuration for the driver. |
Returns
Type | Description |
---|---|
NetworkDriver | Newly-constructed driver. |
Type Parameters
Name | Description |
---|---|
N | Type of the network interface to use. |
CreatePipeline(Type[])
Create a new pipeline from stage types.
Declaration
public NetworkPipeline CreatePipeline(params Type[] stages)
Parameters
Type | Name | Description |
---|---|---|
Type[] | stages | Array of stages the pipeline should contain. |
Returns
Type | Description |
---|---|
NetworkPipeline |
Remarks
The order of the different stages is important, as that is the order in which the stages will process a packet when sending messages (the reverse order is used when processing received packets).
Exceptions
Type | Condition |
---|---|
InvalidOperationException | If called after the driver has established connections or before it is created. Note this is only thrown if safety checks are enabled (i.e. in the editor). |
CreatePipeline(NativeArray<NetworkPipelineStageId>)
Create a new pipeline from stage IDs.
Declaration
public NetworkPipeline CreatePipeline(NativeArray<NetworkPipelineStageId> stages)
Parameters
Type | Name | Description |
---|---|---|
NativeArray<NetworkPipelineStageId> | stages | Array of stage IDs the pipeline should contain. |
Returns
Type | Description |
---|---|
NetworkPipeline |
Remarks
The order of the different stages is important, as that is the order in which the stages will process a packet when sending messages (the reverse order is used when processing received packets).
Note that this method is Burst-compatible. Note also that no reference to the native array is kept internally by the driver. It is thus safe to dispose of it immediately after calling this method (or to use a temporary allocation for the array).
Exceptions
Type | Condition |
---|---|
InvalidOperationException | If called after the driver has established connections or before it is created. Note this is only thrown if safety checks are enabled (i.e. in the editor). |
Disconnect(NetworkConnection)
Close a connection. Note that to properly notify a peer of this disconnection, it is required to schedule at least one update with ScheduleUpdate(JobHandle) and complete it. Failing to do could leave the remote peer unaware that the connection has been closed (however it will time out on its own after a while).
Declaration
public int Disconnect(NetworkConnection connection)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | connection | Connection to close. |
Returns
Type | Description |
---|---|
Int32 | 0 on success, a negative value on error. |
Dispose()
Declaration
public void Dispose()
Implements
EndSend(DataStreamWriter)
Enqueue a send operation for the data in the given DataStreamWriter, which must have been obtained by a prior call to BeginSend(NetworkPipeline, NetworkConnection, out DataStreamWriter, Int32).
Declaration
public int EndSend(DataStreamWriter writer)
Parameters
Type | Name | Description |
---|---|---|
DataStreamWriter | writer | DataStreamWriter to send. |
Returns
Type | Description |
---|---|
Int32 | The number of bytes to be sent on success, a negative value on error. |
Remarks
This method doesn't actually send anything on the wire. It simply enqueues the send operation, which will be performed in the next ScheduleFlushSend(JobHandle) or ScheduleUpdate(JobHandle) job.
GetConnectionState(NetworkConnection)
Get the current state of the given connection.
Declaration
public NetworkConnection.State GetConnectionState(NetworkConnection connection)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | connection | Connection to get the state of. |
Returns
Type | Description |
---|---|
NetworkConnection.State | State of the connection. |
GetEventQueueSizeForConnection(NetworkConnection)
Returns the size of the event queue for a specific connection. This is the number of events that could be popped with PopEventForConnection(NetworkConnection, out DataStreamReader).
Declaration
public int GetEventQueueSizeForConnection(NetworkConnection connection)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | connection | Connection to get the event queue size of. |
Returns
Type | Description |
---|---|
Int32 | Number of events in the connection's event queue. |
GetLocalEndpoint()
Get the local endpoint used by the driver (the endpoint remote peers will use to reach this driver).
Declaration
public NetworkEndpoint GetLocalEndpoint()
Returns
Type | Description |
---|---|
NetworkEndpoint | The local endpoint of the driver. |
Remarks
The returned value should not be assumed to be constant for a given connection, as it is possible for remote peers to change address during the course of a session (e.g. if a mobile client changes IP address because they're hopping between cell towers).
GetPipelineBuffers(NetworkPipeline, NetworkPipelineStageId, NetworkConnection, out NativeArray<Byte>, out NativeArray<Byte>, out NativeArray<Byte>)
Get the low-level pipeline buffers for a given pipeline stage on a given pipeline and for a given connection. Can be used to extract information from a pipeline at runtime. Note that this is a low-level API which is not recommended for general use.
Declaration
public void GetPipelineBuffers(NetworkPipeline pipeline, NetworkPipelineStageId stageId, NetworkConnection connection, out NativeArray<byte> readProcessingBuffer, out NativeArray<byte> writeProcessingBuffer, out NativeArray<byte> sharedBuffer)
Parameters
Type | Name | Description |
---|---|---|
NetworkPipeline | pipeline | Pipeline to get the buffers from. |
NetworkPipelineStageId | stageId | Pipeline stage to get the buffers from. |
NetworkConnection | connection | Connection for which to get the pipeline buffers. |
NativeArray<Byte> | readProcessingBuffer | Buffer used by the receive method of the pipeline. |
NativeArray<Byte> | writeProcessingBuffer | Buffer used by the send method of the pipeline. |
NativeArray<Byte> | sharedBuffer | Buffer used by both receive and send methods of the pipeline. |
Exceptions
Type | Condition |
---|---|
InvalidOperationException | If the connection is invalid. |
GetRemoteEndpoint(NetworkConnection)
Get the remote endpoint of a connection (the endpoint used to reach the remote peer on the connection).
Declaration
public NetworkEndpoint GetRemoteEndpoint(NetworkConnection connection)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | connection | Connection to get the endpoint of. |
Returns
Type | Description |
---|---|
NetworkEndpoint | The remote endpoint of the connection. |
Remarks
The returned value should not be assumed to be constant for a given connection, as it is possible for remote peers to change address during the course of a session (e.g. if a mobile client changes IP address because they're hopping between cell towers).
Listen()
Set the driver to Listen for incomming connections
Declaration
public int Listen()
Returns
Type | Description |
---|---|
Int32 | Returns 0 on success. |
Exceptions
Type | Condition |
---|---|
InvalidOperationException | If the driver is not created properly |
InvalidOperationException | If listen is called more then once on the driver |
InvalidOperationException | If bind has not been called before calling Listen. |
InvalidOperationException | If called on WebGL when not using Relay. |
LocalEndPoint()
Obsolete. Use GetLocalEndpoint() instead.
Declaration
[Obsolete("LocalEndPoint has been renamed to GetLocalEndpoint. (UnityUpgradable) -> GetLocalEndpoint()", false)]
public NetworkEndpoint LocalEndPoint()
Returns
Type | Description |
---|---|
NetworkEndpoint |
MaxHeaderSize(NetworkPipeline)
Get the maximum size of headers when sending on the given pipeline.
Declaration
public int MaxHeaderSize(NetworkPipeline pipe)
Parameters
Type | Name | Description |
---|---|---|
NetworkPipeline | pipe | Pipeline to get the header size for. |
Returns
Type | Description |
---|---|
Int32 | The maximum size of the headers on the given pipeline. |
Remarks
Only accounts for the Unity Transport headers (no UDP or IP).
PopEvent(out NetworkConnection, out DataStreamReader)
Pops the next event from the event queue, Empty will be returned if there are no more events to pop.
Declaration
public NetworkEvent.Type PopEvent(out NetworkConnection connection, out DataStreamReader reader)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | connection | Connection on which the event occured. |
DataStreamReader | reader | DataStreamReader from which the event data (e.g. payload) can be read from. |
Returns
Type | Description |
---|---|
NetworkEvent.Type | The type of the event popped. |
Remarks
The reader
obtained from this method will contain different things for different
event types. For Data, it contains the actual received
payload. For Disconnect, it contains a single byte
identifying the reason for the disconnection (see DisconnectReason).
For other event types, it contains nothing.
PopEvent(out NetworkConnection, out DataStreamReader, out NetworkPipeline)
Pops the next event from the event queue, Empty will be returned if there are no more events to pop.
Declaration
public NetworkEvent.Type PopEvent(out NetworkConnection connection, out DataStreamReader reader, out NetworkPipeline pipe)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | connection | Connection on which the event occured. |
DataStreamReader | reader | DataStreamReader from which the event data (e.g. payload) can be read from. |
NetworkPipeline | pipe | Pipeline on which the data event was received. |
Returns
Type | Description |
---|---|
NetworkEvent.Type | The type of the event popped. |
Remarks
The reader
obtained from this method will contain different things for different
event types. For Data, it contains the actual received
payload. For Disconnect, it contains a single byte
identifying the reason for the disconnection (see DisconnectReason).
For other event types, it contains nothing.
PopEventForConnection(NetworkConnection, out DataStreamReader)
Pops the next event from the event queue for the given connection, Empty will be returned if there are no more events.
Declaration
public NetworkEvent.Type PopEventForConnection(NetworkConnection connection, out DataStreamReader reader)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | connection | Connection for which to pop the event. |
DataStreamReader | reader | DataStreamReader from which the event data (e.g. payload) can be read from. |
Returns
Type | Description |
---|---|
NetworkEvent.Type | The type of the event popped. |
Remarks
The reader
obtained from this method will contain different things for different
event types. For Data, it contains the actual received
payload. For Disconnect, it contains a single byte
identifying the reason for the disconnection (see DisconnectReason).
For other event types, it contains nothing.
PopEventForConnection(NetworkConnection, out DataStreamReader, out NetworkPipeline)
Pops the next event from the event queue for the given connection, Empty will be returned if there are no more events.
Declaration
public NetworkEvent.Type PopEventForConnection(NetworkConnection connection, out DataStreamReader reader, out NetworkPipeline pipe)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | connection | Connection for which to pop the event. |
DataStreamReader | reader | DataStreamReader from which the event data (e.g. payload) can be read from. |
NetworkPipeline | pipe | Pipeline on which the data event was received. |
Returns
Type | Description |
---|---|
NetworkEvent.Type | The type of the event popped. |
Remarks
The reader
obtained from this method will contain different things for different
event types. For Data, it contains the actual received
payload. For Disconnect, it contains a single byte
identifying the reason for the disconnection (see DisconnectReason).
For other event types, it contains nothing.
RegisterPipelineStage<T>(T)
Register a custom pipeline stage.
Declaration
public void RegisterPipelineStage<T>(T stage)
where T : struct, INetworkPipelineStage
Parameters
Type | Name | Description |
---|---|---|
T | stage | An instance of the pipeline stage. |
Type Parameters
Name | Description |
---|---|
T | Type of the pipeline stage (must be unmanaged). |
Remarks
Can only be called before a driver is bound (see Bind(NetworkEndpoint)).
Note that the default pipeline stages (FragmentationPipelineStage, ReliableSequencedPipelineStage, UnreliableSequencedPipelineStage, and SimulatorPipelineStage) don't need to be registered. Registering a pipeline stage is only required for custom ones.
Exceptions
Type | Condition |
---|---|
InvalidOperationException | If the driver is not created or bound. Note that this is only thrown if safety checks are enabled (i.e. in the editor). Otherwise the pipeline is registered anyway (with likely erroneous behavior down the line). |
RemoteEndPoint(NetworkConnection)
Obsolete. Use GetRemoteEndpoint(NetworkConnection) instead.
Declaration
[Obsolete("RemoteEndPoint has been renamed to GetRemoteEndpoint. (UnityUpgradable) -> GetRemoteEndpoint(*)", false)]
public NetworkEndpoint RemoteEndPoint(NetworkConnection id)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | id |
Returns
Type | Description |
---|---|
NetworkEndpoint |
ScheduleFlushSend(JobHandle)
Schedule a send job. This job is basically a subset of the update job (see ScheduleUpdate(JobHandle)) and only takes care of sending packets queued with EndSend(DataStreamWriter). It should be lightweight enough to schedule multiple times per tick to improve latency if there's a significant amount of packets being sent.
Declaration
public JobHandle ScheduleFlushSend(JobHandle dependency = default(JobHandle))
Parameters
Type | Name | Description |
---|---|---|
JobHandle | dependency | Job to depend on. |
Returns
Type | Description |
---|---|
JobHandle | Handle to the send job. |
ScheduleUpdate(JobHandle)
Schedule an update job. This job will process incoming packets and check timeouts (queueing up the relevant events to be consumed by PopEvent(out NetworkConnection, out DataStreamReader) and Accept()) and will send any packets queued with EndSend(DataStreamWriter). This job should generally be scheduled once per tick.
Declaration
public JobHandle ScheduleUpdate(JobHandle dependency = default(JobHandle))
Parameters
Type | Name | Description |
---|---|---|
JobHandle | dependency | Job to depend on. |
Returns
Type | Description |
---|---|
JobHandle | Handle to the update job. |
ToConcurrent()
Create a NetworkDriver.Concurrent copy of the NetworkDriver
.
Declaration
public NetworkDriver.Concurrent ToConcurrent()
Returns
Type | Description |
---|---|
NetworkDriver.Concurrent | A NetworkDriver.Concurrent instance for the driver. |