connect static method
Create a new WebSocket connection using dart:io WebSocket.
The URL supplied in url
must use the scheme ws or wss.
If provided, the protocols
argument indicates that subprotocols that
the peer is able to select. See
RFC-6455 1.9.
Implementation
static Future<IOWebSocket> connect(Uri url,
{Iterable<String>? protocols}) async {
if (!url.isScheme('ws') && !url.isScheme('wss')) {
throw ArgumentError.value(
url, 'url', 'only ws: and wss: schemes are supported');
}
final io.WebSocket webSocket;
try {
webSocket =
await io.WebSocket.connect(url.toString(), protocols: protocols);
} on io.WebSocketException catch (e) {
throw WebSocketException(e.message);
}
if (webSocket.protocol != null &&
!(protocols ?? []).contains(webSocket.protocol)) {
// dart:io WebSocket does not correctly validate the returned protocol.
// See https://github.com/dart-lang/sdk/issues/55106
await webSocket.close(1002); // protocol error
throw WebSocketException(
'unexpected protocol selected by peer: ${webSocket.protocol}');
}
return IOWebSocket._(webSocket);
}