dial method
Dials the addresses in parallel and returns the first successful connection
Implementation
Future<Conn> dial() async {
if (_addrs.isEmpty) {
throw Exception('No addresses to dial');
}
// Create a completer for the first successful connection
final completer = Completer<Conn>();
// Keep track of errors
final errors = <Exception>[];
// Keep track of how many dials are in progress
var dialsInProgress = _addrs.length;
// Dial each address in parallel
for (final addr in _addrs) {
_dialAddr(addr).then((conn) {
// If we haven't completed yet, complete with this connection
if (!completer.isCompleted) {
completer.complete(conn);
}
}).catchError((error) {
// Add the error to our list
errors.add(error is Exception ? error : Exception(error.toString()));
// Decrement the dials in progress
dialsInProgress--;
// If all dials have failed, complete with an error
if (dialsInProgress == 0 && !completer.isCompleted) {
completer.completeError(Exception('Failed to dial any address: ${errors.join(', ')}'));
}
});
}
return completer.future;
}