closeWithError method
Closes the connection with an error code and reason. Sends a CONNECTION_CLOSE frame to the peer before terminating.
Implementation
Future<void> closeWithError(int errorCode, String reason, {int frameType = 0}) async {
if (_closing) return;
_closing = true;
try {
// Send CONNECTION_CLOSE frame
final closeFrame = ConnectionCloseFrame(
errorCode: errorCode,
frameType: frameType,
reasonPhrase: reason,
);
final closePacket = UDXPacket(
destinationCid: cids.remoteCid,
sourceCid: cids.localCid,
destinationStreamId: 0,
sourceStreamId: 0,
sequence: 0,
frames: [closeFrame],
);
try {
send(closePacket.toBytes());
// Small delay to ensure CONNECTION_CLOSE is sent
await Future.delayed(Duration(milliseconds: 100));
} catch (e) {
// Ignore send errors during close
}
// Close all streams
final streamIds = List<int>.from(_registeredStreams.keys);
for (final streamId in streamIds) {
final stream = _registeredStreams[streamId];
if (stream != null) {
await stream.close();
}
}
_registeredStreams.clear();
multiplexer.removeSocket(cids.localCid);
_packetManager.destroy();
_congestionController.destroy();
emit('close', {'error': errorCode, 'reason': reason});
} catch (e) {
emit('error', e);
rethrow;
} finally {
super.close();
}
}