-
Notifications
You must be signed in to change notification settings - Fork 382
Implement WebSocket for the browser #1142
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+370
−16
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
7756049
v1
brianquinlan 0b06c9f
Style
brianquinlan e1a1a56
Comments
brianquinlan 3fe72a4
Update pkgs/web_socket/lib/src/browser_web_socket.dart
brianquinlan a04d018
Update pkgs/web_socket/lib/src/browser_web_socket.dart
brianquinlan 9223ab3
Fixes
brianquinlan 18f3934
Merge branch 'htmlwebsocket' of github.com:brianquinlan/http into htm…
brianquinlan f02516d
Copyright.
brianquinlan 8226eb1
Fix
brianquinlan a9398ee
Merge branch 'master' into htmlwebsocket
brianquinlan 7795eea
Update dart.yml
brianquinlan 39a6ff7
Update disconnect_after_upgrade_tests.dart
brianquinlan 4b9425e
Linux and no wasm
brianquinlan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file | ||
// for details. All rights reserved. Use of this source code is governed by a | ||
// BSD-style license that can be found in the LICENSE file. | ||
|
||
export 'src/browser_web_socket.dart' show BrowserWebSocket; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,5 @@ | ||
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file | ||
// for details. All rights reserved. Use of this source code is governed by a | ||
// BSD-style license that can be found in the LICENSE file. | ||
|
||
export 'src/io_web_socket.dart' show IOWebSocket; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file | ||
// for details. All rights reserved. Use of this source code is governed by a | ||
// BSD-style license that can be found in the LICENSE file. | ||
|
||
import 'dart:async'; | ||
brianquinlan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
import 'dart:js_interop'; | ||
import 'dart:typed_data'; | ||
|
||
import 'package:web/web.dart' as web; | ||
|
||
import '../web_socket.dart'; | ||
import 'utils.dart'; | ||
|
||
/// A [WebSocket] using the browser WebSocket API. | ||
/// | ||
/// Usable when targeting the browser using either JavaScript or WASM. | ||
class BrowserWebSocket implements WebSocket { | ||
final web.WebSocket _webSocket; | ||
final _events = StreamController<WebSocketEvent>(); | ||
|
||
static Future<BrowserWebSocket> connect(Uri url) async { | ||
final webSocket = web.WebSocket(url.toString())..binaryType = 'arraybuffer'; | ||
final browserSocket = BrowserWebSocket._(webSocket); | ||
final webSocketConnected = Completer<BrowserWebSocket>(); | ||
|
||
if (webSocket.readyState == web.WebSocket.OPEN) { | ||
webSocketConnected.complete(browserSocket); | ||
} else { | ||
if (webSocket.readyState == web.WebSocket.CLOSING || | ||
webSocket.readyState == web.WebSocket.CLOSED) { | ||
webSocketConnected.completeError(WebSocketException( | ||
'Unexpected WebSocket state: ${webSocket.readyState}, ' | ||
'expected CONNECTING (0) or OPEN (1)')); | ||
} else { | ||
// The socket API guarantees that only a single open event will be | ||
// emitted. | ||
unawaited(webSocket.onOpen.first.then((_) { | ||
webSocketConnected.complete(browserSocket); | ||
})); | ||
} | ||
} | ||
|
||
unawaited(webSocket.onError.first.then((e) { | ||
// Unfortunately, the underlying WebSocket API doesn't expose any | ||
// specific information about the error itself. | ||
if (!webSocketConnected.isCompleted) { | ||
final error = WebSocketException('Failed to connect WebSocket'); | ||
webSocketConnected.completeError(error); | ||
} else { | ||
browserSocket._closed(1006, 'error'); | ||
} | ||
})); | ||
|
||
webSocket.onMessage.listen((e) { | ||
if (browserSocket._events.isClosed) return; | ||
|
||
final eventData = e.data!; | ||
late WebSocketEvent data; | ||
if (eventData.typeofEquals('string')) { | ||
data = TextDataReceived((eventData as JSString).toDart); | ||
} else if (eventData.typeofEquals('object') && | ||
(eventData as JSObject).instanceOfString('ArrayBuffer')) { | ||
data = BinaryDataReceived( | ||
(eventData as JSArrayBuffer).toDart.asUint8List()); | ||
} else { | ||
throw StateError('unexpected message type: ${eventData.runtimeType}'); | ||
} | ||
browserSocket._events.add(data); | ||
}); | ||
|
||
unawaited(webSocket.onClose.first.then((event) { | ||
if (!webSocketConnected.isCompleted) { | ||
webSocketConnected.complete(browserSocket); | ||
} | ||
browserSocket._closed(event.code, event.reason); | ||
})); | ||
|
||
return webSocketConnected.future; | ||
} | ||
|
||
void _closed(int? code, String? reason) { | ||
if (_events.isClosed) return; | ||
_events.add(CloseReceived(code, reason ?? '')); | ||
unawaited(_events.close()); | ||
} | ||
|
||
BrowserWebSocket._(this._webSocket); | ||
|
||
@override | ||
void sendBytes(Uint8List b) { | ||
if (_events.isClosed) { | ||
throw StateError('WebSocket is closed'); | ||
} | ||
// Silently discards the data if the connection is closed. | ||
_webSocket.send(b.jsify()!); | ||
} | ||
|
||
@override | ||
void sendText(String s) { | ||
if (_events.isClosed) { | ||
throw StateError('WebSocket is closed'); | ||
} | ||
// Silently discards the data if the connection is closed. | ||
_webSocket.send(s.jsify()!); | ||
} | ||
|
||
@override | ||
Future<void> close([int? code, String? reason]) async { | ||
if (_events.isClosed) { | ||
throw StateError('WebSocket is closed'); | ||
} | ||
|
||
checkCloseCode(code); | ||
checkCloseReason(reason); | ||
|
||
unawaited(_events.close()); | ||
if ((code, reason) case (final closeCode?, final closeReason?)) { | ||
_webSocket.close(closeCode, closeReason); | ||
} else if (code case final closeCode?) { | ||
_webSocket.close(closeCode); | ||
} else { | ||
_webSocket.close(); | ||
} | ||
} | ||
|
||
@override | ||
Stream<WebSocketEvent> get events => _events.stream; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.