connect method

  1. @override
Future<WebSocketSession> connect(
  1. Uri url, {
  2. HttpHeaders? headers,
  3. List<String> protocols = const [],
  4. 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 {
  await Future<void>.delayed(Duration.zero);
  if (_failures.isNotEmpty) {
    // Any object can be prepared as the failure (failNextConnect).
    // ignore: only_throw_errors
    throw _failures.removeFirst();
  }
  final socket = MockWebSocket._(
    url,
    headers?.copy() ?? HttpHeaders(),
    List.unmodifiable(protocols),
  );
  _connections.add(socket);
  if (_waiting.isNotEmpty) {
    _taken++;
    _waiting.removeFirst().complete(socket);
  }
  return socket;
}