WebSocket class abstract
A two-way communication object for WebSocket clients. Establishes a WebSocket connection, sends data or streams of data to the server, and receives data from the server.
This class mirrors the native Dart WebSocket API from the dart:io library. The benefit is that it's platform agnostic and can be used on the server or in the browser - so you can write libraries or APIs that can run in either place just by building them on WebSocket.
To establish a connection, use the static connect method:
import 'package:w_transport/w_transport.dart';
main() async {
Uri uri = Uri.parse('ws://echo.websocket.org');
WSocket webSocket = await WSocket.connect(uri);
}
Once the connection has been established, data can be sent to server and the connection can be listened to. WSocket is a stream and a stream sink, so sending and receiving data is the same as interacting with a sink and a stream, respectively.
Uri uri = Uri.parse('ws://echo.websocket.org');
WSocket webSocket = await WSocket.connect(uri);
// Send data
String data = 'data';
Stream stream = ...;
webSocket.add(data);
webSocket.addStream(stream);
// Receive data
webSocket.listen((data) {
print(data);
});
Finally, you can determine when the web socket connection has been closed in a few different ways:
Uri uri = Uri.parse('ws://echo.websocket.org');
WSocket webSocket = await WSocket.connect(uri);
// "done" is a Future
webSocket.done.then((_) { ... });
// calling "close()" returns the same Future
webSocket.close().then((_) { ... });
// registering an "onDone()" handler also works
webSocket.listen((_) {}, onDone: () { ... });
Note: In order to leverage SockJS, you will need to load the sockjs.js
library first. See https://github.com/workiva/sockjs_client_wrapper#usage
- Implemented types
- Implementers
Constructors
Properties
- closeCode → int?
-
The close code set when the WebSocket connection is closed. If there is
no close code available this property will be
null
.no setter - closeReason → String?
-
The close reason set when the WebSocket connection is closed. If there is
no close reason available this property will be
null
.no setter -
done
→ Future<
Null> -
Future that resolves when this WebSocket connection has completely closed.
no setteroverride
- first → Future
-
The first element of this stream.
no setterinherited
- hashCode → int
-
The hash code for this object.
no setterinherited
- isBroadcast → bool
-
Whether this stream is a broadcast stream.
no setterinherited
-
isEmpty
→ Future<
bool> -
Whether this stream contains any elements.
no setterinherited
- last → Future
-
The last element of this stream.
no setterinherited
-
length
→ Future<
int> -
The number of elements in this stream.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- single → Future
-
The single element of this stream.
no setterinherited
Methods
-
add(
dynamic message) → void -
Sends a message over the WebSocket connection.
override
-
addError(
Object errorEvent, [StackTrace? stackTrace]) → void -
Add an error to the sink. This will cause the WebSocket connection to close.
override
-
addStream(
Stream stream) → Future< Null> -
Adds a stream of data to send over the WebSocket connection.
This will wait for the stream to complete, sending each element
as it is received.
override
-
any(
bool test(dynamic element)) → Future< bool> -
Checks whether
test
accepts any element provided by this stream.inherited -
asBroadcastStream(
{void onListen(StreamSubscription subscription)?, void onCancel(StreamSubscription subscription)?}) → Stream -
Returns a multi-subscription stream that produces the same events as this.
inherited
-
asyncExpand<
E> (Stream< E> ? convert(dynamic event)) → Stream<E> -
Transforms each element into a sequence of asynchronous events.
inherited
-
asyncMap<
E> (FutureOr< E> convert(dynamic event)) → Stream<E> -
Creates a new stream with each data event of this stream asynchronously
mapped to a new event.
inherited
-
cast<
R> () → Stream< R> -
Adapt this stream to be a
Stream<R>
.inherited -
close(
[int? code, String? reason]) → Future< Null> -
Closes the WebSocket connection. Optionally set
code
andreason
to send close information to the remote peer.override -
contains(
Object? needle) → Future< bool> -
Returns whether
needle
occurs in the elements provided by this stream.inherited -
distinct(
[bool equals(dynamic previous, dynamic next)?]) → Stream -
Skips data events if they are equal to the previous data event.
inherited
-
drain<
E> ([E? futureValue]) → Future< E> -
Discards all data on this stream, but signals when it is done or an error
occurred.
inherited
-
elementAt(
int index) → Future -
Returns the value of the
index
th data event of this stream.inherited -
every(
bool test(dynamic element)) → Future< bool> -
Checks whether
test
accepts all elements provided by this stream.inherited -
expand<
S> (Iterable< S> convert(dynamic element)) → Stream<S> -
Transforms each element of this stream into a sequence of elements.
inherited
-
firstWhere(
bool test(dynamic element), {dynamic orElse()?}) → Future -
Finds the first element of this stream matching
test
.inherited -
fold<
S> (S initialValue, S combine(S previous, dynamic element)) → Future< S> -
Combines a sequence of values by repeatedly applying
combine
.inherited -
forEach(
void action(dynamic element)) → Future< void> -
Executes
action
on each element of this stream.inherited -
handleError(
Function onError, {bool test(dynamic error)?}) → Stream -
Creates a wrapper Stream that intercepts some errors from this stream.
inherited
-
join(
[String separator = ""]) → Future< String> -
Combines the string representation of elements into a single string.
inherited
-
lastWhere(
bool test(dynamic element), {dynamic orElse()?}) → Future -
Finds the last element in this stream matching
test
.inherited -
listen(
void onData(dynamic event)?, {Function? onError, void onDone()?, bool? cancelOnError}) → StreamSubscription -
Adds a subscription to this stream.
inherited
-
map<
S> (S convert(dynamic event)) → Stream< S> -
Transforms each element of this stream into a new stream event.
inherited
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
pipe(
StreamConsumer streamConsumer) → Future -
Pipes the events of this stream into
streamConsumer
.inherited -
reduce(
dynamic combine(dynamic previous, dynamic element)) → Future -
Combines a sequence of values by repeatedly applying
combine
.inherited -
singleWhere(
bool test(dynamic element), {dynamic orElse()?}) → Future -
Finds the single element in this stream matching
test
.inherited -
skip(
int count) → Stream -
Skips the first
count
data events from this stream.inherited -
skipWhile(
bool test(dynamic element)) → Stream -
Skip data events from this stream while they are matched by
test
.inherited -
take(
int count) → Stream -
Provides at most the first
count
data events of this stream.inherited -
takeWhile(
bool test(dynamic element)) → Stream -
Forwards data events while
test
is successful.inherited -
timeout(
Duration timeLimit, {void onTimeout(EventSink sink)?}) → Stream -
Creates a new stream with the same events as this stream.
inherited
-
toList(
) → Future< List> -
Collects all elements of this stream in a
List
.inherited -
toSet(
) → Future< Set> -
Collects the data of this stream in a
Set
.inherited -
toString(
) → String -
A string representation of this object.
inherited
-
transform<
S> (StreamTransformer< dynamic, S> streamTransformer) → Stream<S> -
Applies
streamTransformer
to this stream.inherited -
where(
bool test(dynamic event)) → Stream -
Creates a new stream from this stream that discards some elements.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
connect(
Uri uri, {Map< String, dynamic> ? headers, Iterable<String> ? protocols, TransportPlatform? transportPlatform}) → Future<WebSocket?> -
Create a new WebSocket connection. The given
uri
must use the schemews
orwss
. -
getGlobalEventMonitor(
) → GlobalWebSocketMonitor - Returns a monitor that provides streams of events for all WebSockets constructed via w_transport.