connect method
Future<WebSocketSession>
connect(
- Uri url, {
- HttpHeaders? headers,
- List<
String> protocols = const [], - Duration? timeout,
override
Opens a connection to url (ws: or wss:) and completes once the
handshake has succeeded.
headers go with the handshake request, typically Authorization.
protocols are the subprotocols offered to the server
(Sec-WebSocket-Protocol); the one it picks is
WebSocketSession.acceptedProtocol. timeout limits the handshake;
null leaves it to the platform.
Fails with a WebSocketException when the server cannot be reached,
refuses the handshake, or does not answer within timeout (then
isTimeout is set).
Browsers cannot send headers with the handshake, so in the browser a
non-empty headers fails at once. Pass a token as a query parameter
or a protocol there instead.
Implementation
@override
Future<WebSocketSession> connect(
Uri url, {
HttpHeaders? headers,
List<String> protocols = const [],
Duration? timeout,
}) async {
final handshake = _handshake(url, headers, protocols);
try {
return timeout == null
? await handshake
: await handshake.timeout(
timeout,
onTimeout: () {
// Close the socket if the handshake completes late.
unawaited(
handshake.then((s) => s.close(), onError: (Object _) {}),
);
throw TimeoutException('handshake', timeout);
},
);
} on TimeoutException catch (error) {
throw WebSocketException(
'no handshake within ${timeout!.inMilliseconds} ms',
url: url,
cause: error,
isTimeout: true,
);
} on Object catch (error) {
if (error is WebSocketException) {
rethrow;
}
throw WebSocketException(
'cannot connect: $error',
url: url,
cause: error,
);
}
}