IOWebSocketChannel.connect constructor

IOWebSocketChannel.connect(
  1. Object url, {
  2. Iterable<String>? protocols,
  3. Map<String, dynamic>? headers,
  4. Duration? pingInterval,
  5. Duration? connectTimeout,
  6. HttpClient? customClient,
})

Creates a new WebSocket connection.

Connects to url using WebSocket.connect and returns a channel that can be used to communicate over the resulting socket. The url may be either a String or a Uri. The protocols and headers parameters are the same as WebSocket.connect.

pingInterval controls the interval for sending ping signals. If a ping message is not answered by a pong message from the peer, the WebSocket is assumed disconnected and the connection is closed with a goingAway code. When a ping signal is sent, the pong message must be received within pingInterval. It defaults to null, indicating that ping messages are disabled.

connectTimeout determines how long to wait for WebSocket.connect before throwing a TimeoutException. If connectTimeout is null then the connection process will never time-out.

If there's an error connecting, the channel's stream emits a WebSocketChannelException wrapping that error and then closes.

Implementation

factory IOWebSocketChannel.connect(
  Object url, {
  Iterable<String>? protocols,
  Map<String, dynamic>? headers,
  Duration? pingInterval,
  Duration? connectTimeout,
  HttpClient? customClient,
}) {
  late IOWebSocketChannel channel;
  final sinkCompleter = WebSocketSinkCompleter();
  var future = WebSocket.connect(
    url.toString(),
    headers: headers,
    protocols: protocols,
    customClient: customClient,
  );
  if (connectTimeout != null) {
    future = future.timeout(connectTimeout);
  }
  final stream = StreamCompleter.fromFuture(future.then((webSocket) {
    webSocket.pingInterval = pingInterval;
    channel._webSocket = webSocket;
    channel._readyCompleter.complete();
    sinkCompleter.setDestinationSink(_IOWebSocketSink(webSocket));
    return webSocket;
  }).catchError((Object error, StackTrace stackTrace) {
    channel._readyCompleter.completeError(error, stackTrace);
    throw WebSocketChannelException.from(error);
  }));
  return channel =
      IOWebSocketChannel._withoutSocket(stream, sinkCompleter.sink);
}