connect method

Future<WebSocketChannel?> connect({
  1. Duration? timeout,
})

Connects the WebSocket. timeout is optional.

The actions sent before it is connected are sent once it is. Throws the error of the connection, or a TimeoutException after timeout.

Implementation

Future<WebSocketChannel?> connect({Duration? timeout}) async {
  if (_closed) throw StateError('The client has been closed.');
  // Not a second socket, whose events would come twice.
  if (_socket != null) return _socket;

  var connecting = getConnectedWebSocket();
  WebSocketChannel socket;
  if (timeout == null) {
    socket = await connecting;
  } else {
    socket = await connecting.timeout(
      timeout,
      onTimeout: () {
        // Closed if it connects after all.
        connecting.then((s) => s.sink.close(), onError: (_) {});
        throw TimeoutException(
          'WebSocket connection exceeded timeout of ${timeout.inMilliseconds} ms',
          timeout,
        );
      },
    );
  }

  if (_closed) {
    await socket.sink.close(status.normalClosure);
    throw StateError('The client has been closed.');
  }

  _socket = socket;
  listen();
  while (_queue.isNotEmpty) {
    socket.sink.add(serialize(_queue.removeFirst()));
  }
  return socket;
}