openSocket method
Future<Socket>
openSocket(
- String host,
- int port, {
- bool secure = false,
- SecurityContext? context,
Opens a socket connection to the specified host
and port
.
host
: The hostname to connect to.port
: The port to connect to.secure
: Whether the connection should be secure (default isfalse
).context
: An optional SecurityContext for secure connections.- Returns a connected Socket or throws an error if the connection fails.
Implementation
Future<Socket> openSocket(String host, int port,
{bool secure = false, SecurityContext? context}) async {
var addresses = _addressesCache[host] ??= await lookupAddress(host);
Object? error;
if (secure) {
for (var i = 0; i < addresses.length; ++i) {
var address = addresses[i];
try {
var socket = await connectSecureSocket(address, port, context);
if (i > 0) {
addresses.removeAt(i);
addresses.insert(0, address);
}
return socket;
} catch (e) {
error = e;
}
}
} else {
for (var i = 0; i < addresses.length; ++i) {
var address = addresses[i];
try {
var socket = await connectSocket(address, port);
if (i > 0) {
addresses.removeAt(i);
addresses.insert(0, address);
}
return socket;
} catch (e) {
error = e;
}
}
}
throw error ?? StateError("Can't connect a socket to> $host:$port");
}