connect static method
Future<WebSocketBrowserConnection>
connect(
- Uri uri, {
- List<
String> protocols = const [], - CancellationToken? cancellationToken,
Implementation
static Future<WebSocketBrowserConnection> connect(Uri uri,
{List<String> protocols = const [],
CancellationToken? cancellationToken}) async {
final token = cancellationToken ?? CancellationToken();
token.throwIfCanceled();
final socket = BrowserWebSocket(
uri.toString(), protocols.map((value) => value.toJS).toList().toJS);
final connection = WebSocketBrowserConnection._(socket);
final opened = Completer<void>();
socket.binaryType = 'arraybuffer';
socket.onopen = ((JSAny? event) {
if (!opened.isCompleted) opened.complete();
}).toJS;
socket.onmessage = ((BrowserMessageEvent event) {
final data = event.data;
if (data.typeofEquals('string')) {
connection._messages.add((data as JSString).toDart);
} else {
connection._messages.add((data as JSArrayBuffer).toDart.asUint8List());
}
}).toJS;
socket.onerror = ((JSAny? event) {
final error = StateError('WebSocket connection failed.');
if (!opened.isCompleted) {
opened.completeError(error);
} else {
connection._messages.addError(error);
}
}).toJS;
socket.onclose = ((JSAny? event) {
if (!opened.isCompleted) {
opened.completeError(StateError('WebSocket closed before opening.'));
}
unawaited(connection._messages.close());
if (!connection._closed.isCompleted) connection._closed.complete();
}).toJS;
final remove = token.onCancel(() => socket.close());
try {
await token.race(opened.future);
return connection;
} catch (_) {
socket.close();
rethrow;
} finally {
remove();
}
}