Class WebRtcTransport
Custom network transport implementation using WebRTC for Unity Netcode. This class handles peer-to-peer connections, data channels, and message routing between clients and server using WebRTC technology.
public class WebRtcTransport : NetworkTransport
- Inheritance
-
WebRtcTransport
Properties
ServerClientId
Gets the client ID representing the server in this transport. In WebRTC, this is typically 0 or a predefined constant.
public override ulong ServerClientId { get; }
Property Value
- ulong
The unique identifier for the server instance.
Remarks
Implementation needed:
- Return a constant value (typically 0) that identifies the server
- This should be consistent across the entire network session Example: return 0;
Methods
DisconnectLocalClient()
Disconnects the local client from the network session. This is called when the local player wants to leave the game.
public override void DisconnectLocalClient()
Remarks
Implementation needed:
- Close all WebRTC peer connections for this client
- Close all data channels associated with the client
- Clean up any pending messages in send/receive queues
- Trigger OnTransportEvent with NetworkEvent.Disconnect
- Call SetDisconnectEvent(DisconnectEvents.Disconnected) from base class
- Reset any local state (connection flags, client ID, etc.)
DisconnectRemoteClient(ulong)
Disconnects a specific remote client from the network session. This is typically called by the server to kick a client.
public override void DisconnectRemoteClient(ulong clientId)
Parameters
clientIdulongThe unique identifier of the client to disconnect.
Remarks
Implementation needed:
- Validate that the clientId exists in your connection dictionary/list
- Close the WebRTC peer connection for the specified client
- Close all data channels associated with this client
- Remove the client from your active connections dictionary
- Trigger OnTransportEvent with NetworkEvent.Disconnect for this client
- Clean up any resources (buffers, pending messages) for this client
- If you're the server, notify other clients about the disconnection if needed
GetCurrentRtt(ulong)
Gets the current Round-Trip Time (RTT) in milliseconds for a specific client. This represents the network latency/ping to that client.
public override ulong GetCurrentRtt(ulong clientId)
Parameters
clientIdulongThe unique identifier of the client to check RTT for.
Returns
- ulong
RTT in milliseconds as an unsigned long.
Remarks
Implementation needed:
- Look up the WebRTC peer connection for the given clientId
- Use WebRTC stats API to get connection statistics
- Extract RTT information from the stats (usually from RTCStatsReport)
- Convert RTT to milliseconds if necessary
- Return the RTT value, or 0 if client not found or stats unavailable
WebRTC typically provides:
- currentRoundTripTime in seconds (multiply by 1000 for ms)
- Or use timestamp-based ping/pong messages for custom RTT calculation
Initialize()
public void Initialize()
Initialize(NetworkManager)
Initializes the transport layer with necessary configuration and dependencies. This is called before starting the server or client.
public override void Initialize(NetworkManager networkManager = null)
Parameters
networkManagerNetworkManagerReference to the Unity Netcode NetworkManager instance.
Remarks
Implementation needed:
- Store the networkManager reference for later use
- Initialize WebRTC configuration (ICE servers, STUN/TURN servers)
- Set up signaling channel/service for WebRTC connection negotiation
- Initialize data structures:
- Dictionary for peer connections (clientId -> RTCPeerConnection)
- Dictionary for data channels (clientId -> RTCDataChannel)
- Queue for incoming network events
- Buffers for send/receive operations
- Set up event handlers for signaling messages
- Configure WebRTC options (ordered/unordered delivery, max retransmits, etc.)
- Initialize any WebRTC platform-specific components
PollEvent(out ulong, out ArraySegment<byte>, out float)
Polls for the next network event in the queue. This is called frequently by Unity Netcode to process incoming messages and connection events.
public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment<byte> payload, out float receiveTime)
Parameters
clientIdulongOutputs the client ID associated with the event.
payloadArraySegment<byte>Outputs the data payload for Data events (message content).
receiveTimefloatOutputs the time when the event was received.
Returns
- NetworkEvent
The type of network event (Nothing, Connect, Data, Disconnect, TransportFailure).
Remarks
Implementation needed:
- Check if there are any events in your event queue
- If queue is empty, return NetworkEvent.Nothing
- Dequeue the next event from your queue
- Set the out parameters based on the event:
- clientId: The client who triggered this event
- payload: The message data (for Data events) or empty for connection events
- receiveTime: Use Time.realtimeSinceStartup or similar
- Return the appropriate NetworkEvent type:
- NetworkEvent.Connect: When a new client connects
- NetworkEvent.Data: When data is received
- NetworkEvent.Disconnect: When a client disconnects
- NetworkEvent.TransportFailure: On transport-level errors
This method is called every frame, so keep it efficient! Events should be queued from WebRTC callbacks (onMessage, onConnection, etc.)
Send(ulong, ArraySegment<byte>, NetworkDelivery)
public override void Send(ulong clientId, ArraySegment<byte> payload, NetworkDelivery networkDelivery)
Parameters
clientIdulongpayloadArraySegment<byte>networkDeliveryNetworkDelivery
Shutdown()
Shuts down the transport layer and cleans up all resources. This is called when stopping the network session completely.
public override void Shutdown()
Remarks
Implementation needed:
- Call ShuttingDown() from base class to set disconnect event
- Close all active WebRTC peer connections
- Close all data channels
- Clear all connection dictionaries and data structures
- Clear event queues
- Disconnect from signaling server/service
- Release any allocated resources (buffers, threads, etc.)
- Reset internal state to allow re-initialization
- Dispose of WebRTC platform-specific components
Ensure this method is idempotent (can be called multiple times safely)
StartClient()
Starts the transport in client mode, initiating connection to a server.
public override bool StartClient()
Returns
- bool
True if client started successfully, false otherwise.
Remarks
Implementation needed:
- Set internal flag to indicate we're running as a client
- Generate or assign a client ID for this instance
- Connect to the signaling server to find the game server
- Create an RTCPeerConnection for connecting to the server
- Create data channels on the peer connection (one per delivery type)
- Set up ICE candidate handlers
- Create and send an offer to the server via signaling
- Wait for server's answer via signaling
- Handle ICE candidate exchange with the server
- Set up data channel event handlers (onOpen, onMessage, onClose, onError)
- When data channel opens, trigger OnTransportEvent with NetworkEvent.Connect
- Return true if initialization succeeds, false on failure
The actual connection is asynchronous, but this method should start the process
StartServer()
Starts the transport in server mode, ready to accept client connections.
public override bool StartServer()
Returns
- bool
True if server started successfully, false otherwise.
Remarks
Implementation needed:
- Set internal flag to indicate we're running as a server
- Set server client ID (typically 0)
- Connect to signaling server to advertise this game session
- Set up signaling message handlers to receive offers from clients
- When an offer arrives from a new client: a. Assign a unique client ID to the new connection b. Create an RTCPeerConnection for this client c. Set remote description from the client's offer d. Create an answer and set it as local description e. Send the answer back to the client via signaling f. Handle ICE candidates for this connection
- Set up data channel event handlers for each client connection
- When a client's data channel opens, trigger OnTransportEvent with NetworkEvent.Connect
- Store each client connection in your connections dictionary
- Return true if server initialization succeeds, false on failure
The server should be able to handle multiple simultaneous client connections