Skip to main content

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.
dtls
*DTLSTransport
required
The DTLS transport instance to send SCTP packets over.
return
*SCTPTransport
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.
return
SCTPTransportState
One of: SCTPTransportStateConnecting, SCTPTransportStateConnected, or SCTPTransportStateClosed.

MaxChannels

func (r *SCTPTransport) MaxChannels() uint16
Returns the maximum number of RTCDataChannels that can be open simultaneously.
return
uint16
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.
return
int
The total buffered bytes.

Capabilities

GetCapabilities

func (r *SCTPTransport) GetCapabilities() SCTPCapabilities
Returns the SCTPCapabilities of the SCTPTransport, including the maximum message size.
return
SCTPCapabilities
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.
capabilities
SCTPCapabilities
required
The SCTP capabilities to use for the connection, including MaxMessageSize. If MaxMessageSize is 0, it defaults to the implementation’s default value.
error
error
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.
error
error
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.
f
func(err error)
required
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.
f
func(err error)
required
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.
return
SCTPTransportStats
Statistics object containing detailed transport metrics.
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:
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:
  1. Accepts the incoming SCTP stream
  2. Parses the channel configuration
  3. Creates a local DataChannel object
  4. Triggers the OnDataChannel handler
  5. Triggers the OnDataChannelOpened handler when ready
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

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

Build docs developers (and LLMs) love