Overview
The SCTPTransport provides details about the SCTP (Stream Control Transmission Protocol) transport layer that manages data channel connections. It handles the establishment and management of the SCTP association over a DTLS transport.
Type Definition
type SCTPTransport struct {
// Contains filtered or unexported fields
}
The SCTPTransport manages the SCTP association, data channel creation, and state transitions.
Creating an SCTPTransport
NewSCTPTransport
func ( api * API ) NewSCTPTransport ( dtls * DTLSTransport ) * SCTPTransport
Creates a new SCTPTransport. This constructor is part of the ORTC API and is not meant to be used together with the basic WebRTC API.
The DTLS transport instance to send SCTP packets over.
The newly created SCTPTransport instance.
sctpTransport := api . NewSCTPTransport ( dtlsTransport )
Properties
Transport
func ( r * SCTPTransport ) Transport () * DTLSTransport
Returns the DTLSTransport instance the SCTPTransport is sending over.
State
func ( r * SCTPTransport ) State () SCTPTransportState
Returns the current state of the SCTPTransport.
One of: SCTPTransportStateConnecting, SCTPTransportStateConnected, or SCTPTransportStateClosed.
MaxChannels
func ( r * SCTPTransport ) MaxChannels () uint16
Returns the maximum number of RTCDataChannels that can be open simultaneously.
The maximum channel count (default: 65535).
BufferedAmount
func ( r * SCTPTransport ) BufferedAmount () int
Returns the total amount (in bytes) of currently buffered user data across all data channels.
The total buffered bytes.
Capabilities
GetCapabilities
func ( r * SCTPTransport ) GetCapabilities () SCTPCapabilities
Returns the SCTPCapabilities of the SCTPTransport, including the maximum message size.
Capabilities object containing MaxMessageSize and other SCTP settings.
caps := sctpTransport . GetCapabilities ()
log . Printf ( "Max message size: %d bytes" , caps . MaxMessageSize )
Lifecycle Management
Start
func ( r * SCTPTransport ) Start ( capabilities SCTPCapabilities ) error
Starts the SCTPTransport. Since both local and remote parties must mutually create an SCTPTransport, SCTP SO (Simultaneous Open) is used to establish a connection over SCTP.
The SCTP capabilities to use for the connection, including MaxMessageSize. If MaxMessageSize is 0, it defaults to the implementation’s default value.
Returns an error if the DTLS transport is not ready, if the SCTP association cannot be established, or if data channels fail to open.
caps := webrtc . SCTPCapabilities {
MaxMessageSize : 262144 , // 256 KB
}
err := sctpTransport . Start ( caps )
if err != nil {
log . Fatal ( err )
}
Calling Start() multiple times is safe; subsequent calls will be ignored if already started.
Stop
func ( r * SCTPTransport ) Stop () error
Stops the SCTPTransport by aborting the SCTP association and closing all data channels.
Returns an error if the stop operation fails.
err := sctpTransport . Stop ()
if err != nil {
log . Printf ( "Error stopping SCTP transport: %v " , err )
}
Event Handlers
OnDataChannel
func ( r * SCTPTransport ) OnDataChannel ( f func ( * DataChannel ))
Sets an event handler invoked when a data channel message arrives from a remote peer.
f
func(*DataChannel)
required
The callback function to invoke when a new data channel is received.
sctpTransport . OnDataChannel ( func ( dc * webrtc . DataChannel ) {
log . Printf ( "New data channel: %s " , dc . Label ())
dc . OnMessage ( func ( msg webrtc . DataChannelMessage ) {
log . Printf ( "Message from %s : %s " , dc . Label (), string ( msg . Data ))
})
})
This handler runs synchronously to allow setup to complete before data channel event handlers are called.
OnDataChannelOpened
func ( r * SCTPTransport ) OnDataChannelOpened ( f func ( * DataChannel ))
Sets an event handler invoked when a data channel is fully opened and ready to use.
f
func(*DataChannel)
required
The callback function to invoke when a data channel opens.
sctpTransport . OnDataChannelOpened ( func ( dc * webrtc . DataChannel ) {
log . Printf ( "Data channel opened: %s (ID: %d )" , dc . Label (), * dc . ID ())
})
OnError
func ( r * SCTPTransport ) OnError ( f func ( err error ))
Sets an event handler invoked when the SCTP Association encounters an error.
The callback function to invoke when an error occurs.
sctpTransport . OnError ( func ( err error ) {
log . Printf ( "SCTP transport error: %v " , err )
})
OnClose
func ( r * SCTPTransport ) OnClose ( f func ( err error ))
Sets an event handler invoked when the SCTP Association closes.
The callback function to invoke when the transport closes. The error parameter will be nil for clean closes.
sctpTransport . OnClose ( func ( err error ) {
if err != nil {
log . Printf ( "SCTP transport closed with error: %v " , err )
} else {
log . Println ( "SCTP transport closed cleanly" )
}
})
Statistics
Stats
func ( r * SCTPTransport ) Stats () SCTPTransportStats
Reports the current statistics of the SCTPTransport.
Statistics object containing detailed transport metrics.
Show SCTPTransportStats Fields
When the statistics were collected.
Always StatsTypeSCTPTransport.
Identifier for this statistics object (typically “sctpTransport”).
Total bytes sent over the SCTP association.
Total bytes received over the SCTP association.
Smoothed round-trip time in seconds.
Current congestion window size in bytes.
Current receiver window size in bytes.
Maximum transmission unit size in bytes.
stats := sctpTransport . Stats ()
log . Printf ( "SCTP Stats:" )
log . Printf ( " Bytes sent: %d " , stats . BytesSent )
log . Printf ( " Bytes received: %d " , stats . BytesReceived )
log . Printf ( " RTT: %.3f seconds" , stats . SmoothedRoundTripTime )
log . Printf ( " Congestion window: %d bytes" , stats . CongestionWindow )
log . Printf ( " MTU: %d bytes" , stats . MTU )
Internal Operations
The SCTPTransport automatically handles several internal operations:
Data Channel ID Generation
The transport automatically generates unique IDs for data channels based on the DTLS role:
Client role : Uses even IDs (0, 2, 4, …)
Server role : Uses odd IDs (1, 3, 5, …)
This ensures no ID conflicts between peers.
When a remote peer creates a data channel, the transport:
Accepts the incoming SCTP stream
Parses the channel configuration
Creates a local DataChannel object
Triggers the OnDataChannel handler
Triggers the OnDataChannelOpened handler when ready
Reliability Configuration
The transport handles different reliability modes:
Reliable ordered : Standard TCP-like behavior
Reliable unordered : All messages delivered, order not guaranteed
Partial reliable with retransmit limit : Limited retransmission attempts
Partial reliable with time limit : Messages expire after time window
Each mode uses different SCTP channel types internally.
Complete Example
ORTC API Example
Statistics Monitoring
package main
import (
" log "
" github.com/pion/webrtc/v4 "
)
func main () {
// Create API with custom settings
api := webrtc . NewAPI ()
// Create DTLS transport (assuming you have ICE transport set up)
dtlsTransport := api . NewDTLSTransport ( iceTransport , nil )
// Create SCTP transport
sctpTransport := api . NewSCTPTransport ( dtlsTransport )
// Set up event handlers
sctpTransport . OnDataChannel ( func ( dc * webrtc . DataChannel ) {
log . Printf ( "New data channel: %s " , dc . Label ())
dc . OnOpen ( func () {
log . Printf ( "Data channel %s opened" , dc . Label ())
})
dc . OnMessage ( func ( msg webrtc . DataChannelMessage ) {
log . Printf ( "Message on %s : %s " , dc . Label (), string ( msg . Data ))
})
})
sctpTransport . OnError ( func ( err error ) {
log . Printf ( "SCTP error: %v " , err )
})
sctpTransport . OnClose ( func ( err error ) {
if err != nil {
log . Printf ( "SCTP closed with error: %v " , err )
} else {
log . Println ( "SCTP closed cleanly" )
}
})
// Start the transport
caps := webrtc . SCTPCapabilities {
MaxMessageSize : 262144 , // 256 KB
}
err := sctpTransport . Start ( caps )
if err != nil {
log . Fatal ( err )
}
// Create a data channel
params := & webrtc . DataChannelParameters {
Label : "my-channel" ,
Ordered : true ,
Protocol : "json" ,
}
dc , err := api . NewDataChannel ( sctpTransport , params )
if err != nil {
log . Fatal ( err )
}
dc . OnOpen ( func () {
log . Println ( "Outgoing channel opened" )
dc . SendText ( "Hello from ORTC!" )
})
// Continue with signaling and connection setup...
}
Configuration Options
The SCTP transport behavior can be customized through the SettingEngine before creating the API:
se := webrtc . SettingEngine {}
// Set maximum receive buffer size
se . SetSCTPMaxReceiveBufferSize ( 2 * 1024 * 1024 ) // 2 MB
// Enable zero checksum (for testing only)
se . SetSCTPZeroChecksum ( true )
// Set RTO max timeout
se . SetSCTPRTOMax ( 800 * time . Millisecond )
// Set minimum congestion window
se . SetSCTPMinCwnd ( 4380 )
// Create API with custom settings
api := webrtc . NewAPI ( webrtc . WithSettingEngine ( se ))
Changing SCTP settings can significantly impact performance and reliability. Only modify these if you understand the implications.
Best Practices
Handle Errors Always set up OnError handlers to catch and handle SCTP association errors gracefully.
Monitor State Check the transport state before performing operations to avoid errors on closed connections.
Configure Limits Set appropriate MaxMessageSize based on your application’s needs and network conditions.
Clean Shutdown Call Stop() when done to properly clean up resources and close all data channels.
DataChannel Individual data channels running over this SCTP transport
DTLSTransport The underlying DTLS transport for secure communication
SCTPCapabilities Capabilities and configuration for SCTP connections
SCTPTransportState State enumeration for transport lifecycle