QuicConnection class

Orchestrates all subsystems of a single QUIC connection.

A QuicConnection represents one QUIC association between a client and a server. It manages the connection state machine, connection IDs, packet number spaces, loss detection, congestion control, flow control, and stream allocation. It is the central hub that incoming frames are dispatched to and from which outgoing packets are built.

Connections are created by a QuicEndpoint (via QuicEndpoint.connect for outbound or automatically for inbound) and progress through the handshake until isEstablished becomes true. Once established, streams can be opened with openBidirectionalStream or openUnidirectionalStream, and data can be read from or written to those streams via the streamManager.

Example

final endpoint = await QuicEndpoint.bind(InternetAddress.anyIPv4, 0);
final conn = await endpoint.connect(remoteAddress, remotePort);

// Wait for handshake completion.
while (!conn.isEstablished) {
  await Future.delayed(Duration(milliseconds: 10));
}

// Open a client-initiated bidirectional stream.
final streamId = conn.openBidirectionalStream();
print('Opened stream $streamId');

// Gracefully close the connection when done.
conn.close();

See also:

  • QuicEndpoint — creates and manages connections.
  • StreamManager — routes STREAM frames to individual streams.
  • RecoveryManager — coordinates loss detection and congestion control.
  • RFC 9000 Section 5 — Connection State Machine.

Constructors

QuicConnection({required ConnectionStateMachine stateMachine, required ConnectionIdManager cidManager, required PacketNumberSpaceManager pnSpaceManager, required RttEstimator rttEstimator, required LossDetector lossDetector, required PtoScheduler ptoScheduler, CongestionController? congestionController, required StreamIdAllocator streamIdAllocator, CryptoFrameAssembler? cryptoAssembler, HandshakeStateMachine? handshakeMachine, KeyManager? keyManager, StreamScheduler? streamScheduler, VersionInformation? versionInformation, bool greaseQuicBit = true, bool ecnEnabled = true, bool allowMigration = true, InternetAddress? preferredAddress, int preferredAddressPort = 0, List<int>? originalDestinationConnectionId, Uint8List? statelessResetToken, List<int>? initialSourceConnectionId, List<int>? retrySourceConnectionId, bool useCubic = false})
Creates a QuicConnection with the given subsystems.

Properties

ackDelayExponent int
getter/setter pair
activeConnectionIdCount int
Number of currently active connection IDs.
no setter
activeConnectionIdLimit int
getter/setter pair
allowMigration bool
Whether the peer is allowed to migrate (RFC 9000 Section 9).
getter/setter pair
alpnProtocols List<String>
ALPN protocols advertised during the TLS handshake (e.g. ['libp2p']).
getter/setter pair
attempt0Rtt bool
getter/setter pair
canSendZeroRtt bool
True if 0-RTT keys are available and early data can be sent.
no setter
ceCounter int
getter/setter pair
cidManager ConnectionIdManager
no setter
congestionController CongestionController
no setter
connectionFlowController FlowController
The connection-level flow controller.
no setter
connectionId List<int>?
Note: ECN codepoint marking at the IP layer (ECT(0)=2, ECT(1)=3) is not implemented because Dart's RawDatagramSocket does not expose platform- specific socket options such as IP_TOS (Linux) or IP_TOS/Traffic Class (Windows). ECN validation via AckEcnFrame is fully supported. The first active connection ID, or null if none have been issued.
no setter
cryptoAssembler → CryptoFrameAssembler?
The crypto frame assembler (null until handshake pipeline is wired).
no setter
ecnEnabled bool
Whether ECN capability is enabled for this connection.
getter/setter pair
ect0Counter int
getter/setter pair
ect1Counter int
getter/setter pair
greaseQuicBit bool
getter/setter pair
handshakeMachine HandshakeStateMachine?
The handshake state machine (null until handshake pipeline is wired).
no setter
hashCode int
The hash code for this object.
no setterinherited
initialMaxData int
getter/setter pair
initialMaxStreamDataBidiLocal int
getter/setter pair
initialMaxStreamDataBidiRemote int
getter/setter pair
initialMaxStreamDataUni int
getter/setter pair
initialMaxStreamsBidi int
getter/setter pair
initialMaxStreamsUni int
getter/setter pair
initialSourceConnectionId List<int>?
Initial source connection ID (0x0f), validation aid.
getter/setter pair
isClosed bool
Whether the connection is fully closed and can no longer send or receive.
no setter
isEcnValidated bool
Whether ECN has been validated for this connection (RFC 9000 Section 13.4.2).
no setter
isEstablished bool
Whether the handshake has completed and the connection is ready for streams.
no setter
isProbingPath bool
True while a path probe initiated by probeNewPath is pending.
no setter
keyManager KeyManager?
The key manager for packet encryption/decryption (null for plaintext mode).
no setter
lastProbePacket Uint8List?
The most recent packet built by probeNewPath, or null if no probe has been initiated.
no setter
lossDetector LossDetector
no setter
maxAckDelay int
getter/setter pair
maxDatagramFrameSize int
getter/setter pair
maxEarlyData int
Maximum amount of early data the server is willing to accept (bytes). Defaults to 0xffff as a conservative limit.
getter/setter pair
maxIdleTimeout int
getter/setter pair
maxUdpPayloadSize int
getter/setter pair
migrationHelper MigrationHelper
The migration helper coordinating path validation.
no setter
negotiatedAlpn String?
The ALPN protocol negotiated by the peer, set after the handshake completes and EncryptedExtensions have been processed.
getter/setter pair
onDatagramReceived Stream<Uint8List>
Stream of received unreliable datagram payloads (RFC 9221).
no setter
originalDestinationConnectionId List<int>?
Original destination connection ID (0x00), sent by server after Retry.
getter/setter pair
pacingCalculator PacingCalculator
no setter
pacingDelayUs int?
The current pacing delay in microseconds, or null if pacing is not currently needed.
no setter
pacingTimerForTest → PacingTimer
The internal pacing timer, exposed for testing.
no setter
preferredAddress InternetAddress?
Preferred address for connection migration (RFC 9000 Section 9.6).
getter/setter pair
preferredAddressPort int
Port for the preferred address.
getter/setter pair
pskTicket Uint8List?
getter/setter pair
pskTicketAgeAdd int?
getter/setter pair
ptoScheduler PtoScheduler
no setter
recoveryManager → RecoveryManager
The recovery manager coordinating loss detection, congestion control, PTO scheduling, and RTT estimation.
no setter
retrySourceConnectionId List<int>?
Retry source connection ID (0x10), sent by server after Retry.
getter/setter pair
rttEstimator RttEstimator
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
sendBudget int
Current anti-amplification send budget.
no setter
sentPacketTracker SentPacketTracker
no setter
shouldPacePackets bool
Whether the connection should pace outgoing packets.
no setter
state ConnectionState
The current state of this connection (e.g. idle, handshaking, established).
no setter
statelessResetToken Uint8List?
Stateless reset token (0x02), 16-byte token for stateless reset.
getter/setter pair
stateMachine ConnectionStateMachine
The connection state machine managing the connection lifecycle.
no setter
streamManager → StreamManager
The stream manager routing STREAM frames.
no setter
streamScheduler StreamScheduler
Set the stream scheduler used by this connection.
no getter
validatedPathCount int
Number of paths that have been successfully validated.
no setter
versionInformation VersionInformation?
getter/setter pair

Methods

abort() → void
Force-close the connection immediately.
allocatePacketNumber(PacketNumberSpace space) int
Allocate a packet number for the given space.
applyPeerTransportParameters(Uint8List bytes) → void
Parse peer transport parameters and update connection state.
buildClientHelloExtensions() List<TlsExtension>
TLS extensions that should be included in the ClientHello for this connection. Returns an early_data extension when attempt0Rtt is enabled and a PSK ticket is available, and an ALPN extension when alpnProtocols is non-empty.
buildEncryptedPacket({required PacketNumberSpace space, required List<Frame> frames, required List<int> dcid, List<int>? scid}) Future<Uint8List>
Build an encrypted outgoing packet for the given space and frames.
buildPacket({required PacketNumberSpace space, required List<Frame> frames, required List<int> dcid, List<int>? scid}) Future<Uint8List>
Build an outgoing packet for the given space and frames, and track it with the recovery manager.
buildTransportParameters() Uint8List
Serialize this connection's transport parameters into the wire format used inside the quic_transport_parameters TLS extension.
buildZeroRttPacket({required List<Frame> frames, required List<int> dcid}) Future<Uint8List>
Build and track an encrypted 0-RTT packet containing frames.
canSend(int bytes) bool
True if bytes can be sent without violating the anti-amplification limit or congestion window.
close() → void
Initiates a graceful close of this connection.
generateNewConnectionIdFrame() Frame
Issue a new connection ID and return a NewConnectionIdFrame.
getPendingChallenge() PathChallengeFrame?
Returns the most recent pending challenge for PATH_RESPONSE generation.
isPathValidated(List<int> pathId) bool
Check if a path is validated.
isPtoExpired(int currentTimeUs) bool
Check if a PTO timer has expired.
isZeroRttCompatibleAcrossVersions(VersionInformation peerInfo) bool
Check whether 0-RTT is compatible with the peer's version information.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
onAckReceived(int spaceIndex, int largestAcked, List<({int gap, int length})> ranges) → void
Record an ACK for packet tracking and update recovery subsystems.
onAddressValidated() → void
Validate peer address after receiving a Retry packet or PATH_RESPONSE. Removes the anti-amplification limit.
onBytesReceived(int bytes) → void
Record bytes received from the peer (for anti-amplification accounting).
onBytesSent(int bytes) → void
Record bytes sent to the peer (for anti-amplification accounting).
onPacketSent(int packetNumber, int sentTimeUs, {bool ackEliciting = true, bool inFlight = true, int sizeInBytes = 0, int spaceIndex = 0}) → void
Register a sent packet with the recovery manager and key manager.
onPathResponseReceived(PathResponseFrame frame) bool
Handle a received PATH_RESPONSE frame.
onPathValidated() → void
Called when a path is validated; increments a counter for stats.
onPtoFired(int currentTimeUs) → void
Handle a PTO firing: update scheduler and return current PTO duration.
openBidirectionalStream() int
Allocates a new client-initiated bidirectional stream ID and creates the send-side stream in the streamManager.
openUnidirectionalStream() int
Allocates a new client-initiated unidirectional stream ID and creates the send-side stream in the streamManager.
probeNewPath(List<int> dcid) Future<void>
Probe a new path by sending a PATH_CHALLENGE frame.
processEncryptedDatagram(Uint8List datagram) Future<int>
Process an incoming encrypted UDP datagram.
processIncomingDatagram(Uint8List datagram) int
Process an incoming UDP datagram, splitting coalesced packets and dispatching frames to the appropriate subsystems.
sendDatagram(Uint8List data) DatagramFrame
Build a DatagramFrame containing data.
sendPathChallenge(List<int> dcid) Future<Uint8List>
Send a PATH_CHALLENGE frame to validate a path.
toString() String
A string representation of this object.
inherited
updateConnectionFlowControl(int newLimit) → void
Update the connection-level flow control limit.
validateAddress() → void
Mark the peer address as validated (removes anti-amplification limit).

Operators

operator ==(Object other) bool
The equality operator.
inherited