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 {
if (headers != null && headers.isNotEmpty) {
throw WebSocketException(
'browsers cannot send headers (${headers.names.join(', ')}) with a '
'WebSocket handshake: pass them as query parameters or a protocol',
url: url,
);
}
final _WebSocket socket;
try {
socket = _WebSocket(
url.toString().toJS,
[for (final protocol in protocols) protocol.toJS].toJS,
)..binaryType = 'arraybuffer'.toJS;
} catch (error) {
throw WebSocketException(
'cannot connect: $error',
url: url,
cause: error,
);
}
final connection = _BrowserSession(socket, url);
final opened = connection._opened.future;
try {
if (timeout == null) {
await opened;
} else {
await opened.timeout(timeout);
}
return connection;
} on TimeoutException catch (error) {
socket.close();
throw WebSocketException(
'no handshake within ${timeout!.inMilliseconds} ms',
url: url,
cause: error,
isTimeout: true,
);
}
}