addConnection method
Future<PeerConnection>
addConnection(
- String address,
- int port, {
- PeerConnectionConfig? connectionConfig,
Add a new peer connection
Implementation
Future<PeerConnection> addConnection(
String address,
int port, {
PeerConnectionConfig? connectionConfig,
}) async {
if (_isShutdown) {
throw ConnectionException('Connection manager is shutdown');
}
final connectionId = '$address:$port';
// Check if connection already exists
if (_connections.containsKey(connectionId)) {
throw ConnectionException('Connection already exists: $connectionId');
}
// Check connection limit
if (_connections.length >= config.maxConnections) {
throw ConnectionException('Maximum connections reached: ${config.maxConnections}');
}
logger.info('Adding connection to $connectionId');
// Create connection
final connection = PeerConnection(
address: address,
port: port,
network: network,
config: connectionConfig ?? config.defaultConnectionConfig,
logger: logger,
);
// Set up event listeners
_setupConnectionListeners(connection, connectionId);
// Add to tracking
_connections[connectionId] = connection;
_reconnectAttempts[connectionId] = 0;
// Attempt to connect
try {
await connection.connect();
logger.info('Successfully connected to $connectionId');
} catch (e) {
// Remove failed connection
_connections.remove(connectionId);
_reconnectAttempts.remove(connectionId);
await connection.close();
rethrow;
}
_connectionAddedController.add(connection);
return connection;
}