WebSocket class
Use the WebSocket interface to connect to a WebSocket, and to send and receive data on that WebSocket.
To use a WebSocket in your web app, first create a WebSocket object, passing the WebSocket URL as an argument to the constructor.
var webSocket = new WebSocket('ws://127.0.0.1:1337/ws');
To send data on the WebSocket, use the send method.
if (webSocket != null && webSocket.readyState == WebSocket.OPEN) {
webSocket.send(data);
} else {
print('WebSocket not connected, message $data not sent');
}
To receive data on the WebSocket, register a listener for message events.
webSocket.on.message.add((MessageEvent e) {
receivedData(e.data);
});
The message event handler receives a MessageEvent object
as its sole argument.
You can also define open, close, and error handlers,
as specified by WebSocketEvents.
For more information, see the WebSockets section of the library tour and Introducing WebSockets, an HTML5Rocks.com tutorial.
@DocsEditable
/**
* Use the WebSocket interface to connect to a WebSocket,
* and to send and receive data on that WebSocket.
*
* To use a WebSocket in your web app, first create a WebSocket object,
* passing the WebSocket URL as an argument to the constructor.
*
* var webSocket = new WebSocket('ws://127.0.0.1:1337/ws');
*
* To send data on the WebSocket, use the [send] method.
*
* if (webSocket != null && webSocket.readyState == WebSocket.OPEN) {
* webSocket.send(data);
* } else {
* print('WebSocket not connected, message $data not sent');
* }
*
* To receive data on the WebSocket, register a listener for message events.
*
* webSocket.on.message.add((MessageEvent e) {
* receivedData(e.data);
* });
*
* The message event handler receives a [MessageEvent] object
* as its sole argument.
* You can also define open, close, and error handlers,
* as specified by [WebSocketEvents].
*
* For more information, see the
* [WebSockets](http://www.dartlang.org/docs/library-tour/#html-websockets)
* section of the library tour and
* [Introducing WebSockets](http://www.html5rocks.com/en/tutorials/websockets/basics/),
* an HTML5Rocks.com tutorial.
*/
@DomName('WebSocket')
@SupportedBrowser(SupportedBrowser.CHROME)
@SupportedBrowser(SupportedBrowser.FIREFOX)
@SupportedBrowser(SupportedBrowser.IE, '10')
@SupportedBrowser(SupportedBrowser.SAFARI)
class WebSocket extends EventTarget native "WebSocket" {
@DomName('WebSocket.closeEvent')
@DocsEditable
static const EventStreamProvider<CloseEvent> closeEvent = const EventStreamProvider<CloseEvent>('close');
@DomName('WebSocket.errorEvent')
@DocsEditable
static const EventStreamProvider<Event> errorEvent = const EventStreamProvider<Event>('error');
@DomName('WebSocket.messageEvent')
@DocsEditable
static const EventStreamProvider<MessageEvent> messageEvent = const EventStreamProvider<MessageEvent>('message');
@DomName('WebSocket.openEvent')
@DocsEditable
static const EventStreamProvider<Event> openEvent = const EventStreamProvider<Event>('open');
@DomName('WebSocket.WebSocket')
@DocsEditable
factory WebSocket(String url, [protocol_OR_protocols]) {
if ((url is String || url == null) && !?protocol_OR_protocols) {
return WebSocket._create_1(url);
}
if ((url is String || url == null) && (protocol_OR_protocols is List<String> || protocol_OR_protocols == null)) {
return WebSocket._create_2(url, protocol_OR_protocols);
}
if ((url is String || url == null) && (protocol_OR_protocols is String || protocol_OR_protocols == null)) {
return WebSocket._create_3(url, protocol_OR_protocols);
}
throw new ArgumentError("Incorrect number or type of arguments");
}
static WebSocket _create_1(url) => JS('WebSocket', 'new WebSocket(#)', url);
static WebSocket _create_2(url, protocol_OR_protocols) => JS('WebSocket', 'new WebSocket(#,#)', url, protocol_OR_protocols);
static WebSocket _create_3(url, protocol_OR_protocols) => JS('WebSocket', 'new WebSocket(#,#)', url, protocol_OR_protocols);
/// Checks if this type is supported on the current platform.
static bool get supported => JS('bool', 'typeof window.WebSocket != "undefined"');
@DomName('WebSocket.CLOSED')
@DocsEditable
static const int CLOSED = 3;
@DomName('WebSocket.CLOSING')
@DocsEditable
static const int CLOSING = 2;
@DomName('WebSocket.CONNECTING')
@DocsEditable
static const int CONNECTING = 0;
@DomName('WebSocket.OPEN')
@DocsEditable
static const int OPEN = 1;
@JSName('URL')
@DomName('WebSocket.URL')
@DocsEditable
final String Url;
@DomName('WebSocket.binaryType')
@DocsEditable
String binaryType;
@DomName('WebSocket.bufferedAmount')
@DocsEditable
final int bufferedAmount;
@DomName('WebSocket.extensions')
@DocsEditable
final String extensions;
@DomName('WebSocket.protocol')
@DocsEditable
final String protocol;
@DomName('WebSocket.readyState')
@DocsEditable
final int readyState;
@DomName('WebSocket.url')
@DocsEditable
final String url;
@JSName('addEventListener')
@DomName('WebSocket.addEventListener')
@DocsEditable
void $dom_addEventListener(String type, EventListener listener, [bool useCapture]) native;
@DomName('WebSocket.close')
@DocsEditable
void close([int code, String reason]) native;
@DomName('WebSocket.dispatchEvent')
@DocsEditable
bool dispatchEvent(Event evt) native;
@JSName('removeEventListener')
@DomName('WebSocket.removeEventListener')
@DocsEditable
void $dom_removeEventListener(String type, EventListener listener, [bool useCapture]) native;
@DomName('WebSocket.send')
@DocsEditable
void send(data) native;
@DomName('WebSocket.onclose')
@DocsEditable
Stream<CloseEvent> get onClose => closeEvent.forTarget(this);
@DomName('WebSocket.onerror')
@DocsEditable
Stream<Event> get onError => errorEvent.forTarget(this);
@DomName('WebSocket.onmessage')
@DocsEditable
Stream<MessageEvent> get onMessage => messageEvent.forTarget(this);
@DomName('WebSocket.onopen')
@DocsEditable
Stream<Event> get onOpen => openEvent.forTarget(this);
}
Extends
Interceptor > EventTarget > WebSocket
Static Properties
const EventStreamProvider<CloseEvent> closeEvent #
static const EventStreamProvider<CloseEvent> closeEvent = const EventStreamProvider<CloseEvent>('close')
const EventStreamProvider<Event> errorEvent #
static const EventStreamProvider<Event> errorEvent = const EventStreamProvider<Event>('error')
const EventStreamProvider<MessageEvent> messageEvent #
static const EventStreamProvider<MessageEvent> messageEvent = const EventStreamProvider<MessageEvent>('message')
const EventStreamProvider<Event> openEvent #
static const EventStreamProvider<Event> openEvent = const EventStreamProvider<Event>('open')
Constructors
factory WebSocket(String url, [protocol_OR_protocols]) #
@DomName('WebSocket.WebSocket')
@DocsEditable
factory WebSocket(String url, [protocol_OR_protocols]) {
if ((url is String || url == null) && !?protocol_OR_protocols) {
return WebSocket._create_1(url);
}
if ((url is String || url == null) && (protocol_OR_protocols is List<String> || protocol_OR_protocols == null)) {
return WebSocket._create_2(url, protocol_OR_protocols);
}
if ((url is String || url == null) && (protocol_OR_protocols is String || protocol_OR_protocols == null)) {
return WebSocket._create_3(url, protocol_OR_protocols);
}
throw new ArgumentError("Incorrect number or type of arguments");
}
Properties
String binaryType #
Blob
objects are being used or "arraybuffer" if ArrayBuffer objects are being used.
String binaryType
final int bufferedAmount #
final int bufferedAmount
final String extensions #
final String extensions
final int hashCode #
Get a hash code for this object.
All objects have hash codes. Hash codes are guaranteed to be the
same for objects that are equal when compared using the equality
operator ==. Other than that there are no guarantees about
the hash codes. They will not be consistent between runs and
there are no distribution guarantees.
If a subclass overrides hashCode it should override the
equality operator as well to maintain consistency.
int get hashCode => Primitives.objectHashCode(this);
final Events on #
This is an ease-of-use accessor for event streams which should only be used when an explicit accessor is not available.
Events get on => new Events(this);
final Stream<CloseEvent> onClose #
readyState changes to CLOSED. The listener receives a CloseEvent named "close".
@DomName('WebSocket.onclose')
@DocsEditable
Stream<CloseEvent> get onClose => closeEvent.forTarget(this);
final Stream<Event> onError #
@DomName('WebSocket.onerror')
@DocsEditable
Stream<Event> get onError => errorEvent.forTarget(this);
final Stream<MessageEvent> onMessage #
MessageEvent named "message".
@DomName('WebSocket.onmessage')
@DocsEditable
Stream<MessageEvent> get onMessage => messageEvent.forTarget(this);
final Stream<Event> onOpen #
readyState changes to OPEN; this indicates that the connection is ready to send and receive data. The event is a simple one with the name "open".
@DomName('WebSocket.onopen')
@DocsEditable
Stream<Event> get onOpen => openEvent.forTarget(this);
final String protocol #
protocols parameter when creating the WebSocket object.
final String protocol
final int readyState #
final int readyState
final Type runtimeType #
A representation of the runtime type of the object.
Type get runtimeType => getRuntimeType(this);
Operators
bool operator ==(other) #
The equality operator.
The default behavior for all Objects is to return true if and
only if this and
other are the same object.
If a subclass overrides the equality operator it should override
the hashCode method as well to maintain consistency.
bool operator ==(other) => identical(this, other);
Methods
void close([int code, String reason]) #
Closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
Parameters
codeOptional- A numeric value indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal "transaction complete" closure) is assumed. See the list of status codes on the
CloseEventpage for permitted values. reasonOptional- A human-readable string explaining why the connection is closing. This string must be no longer than 123 UTF-8 characters.
Exceptions thrown
INVALID_ACCESS_ERR- An invalid
codewas specified. SYNTAX_ERR- The
reasonstring is too long or contains unpaired surrogates.
@DomName('WebSocket.close')
@DocsEditable
void close([int code, String reason]) native;
bool dispatchEvent(Event evt) #
@DomName('WebSocket.dispatchEvent')
@DocsEditable
bool dispatchEvent(Event evt) native;
dynamic noSuchMethod(Invocation invocation) #
noSuchMethod is invoked when users invoke a non-existant method
on an object. The name of the method and the arguments of the
invocation are passed to noSuchMethod in an Invocation.
If noSuchMethod returns a value, that value becomes the result of
the original invocation.
The default behavior of noSuchMethod is to throw a
noSuchMethodError.
dynamic noSuchMethod(Invocation invocation) {
throw new NoSuchMethodError(
this,
_symbolToString(invocation.memberName),
invocation.positionalArguments,
_symbolMapToStringMap(invocation.namedArguments));
}
void send(data) #
Transmits data to the server over the WebSocket connection.
Parameters
data- A text string to send to the server.
Exceptions thrown
INVALID_STATE_ERR- The connection is not currently
OPEN. SYNTAX_ERR- The data is a string that has unpaired surrogates.
Remarks
Gecko's implementation of the send() method differs somewhat from the specification in Gecko 6.0; Gecko returns a boolean indicating whether or not the connection is still open (and, by extension, that the data was successfully queued or transmitted); this is corrected in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5)
. In addition, at this time, Gecko does not support ArrayBuffer or Blob
data types.
@DomName('WebSocket.send')
@DocsEditable
void send(data) native;
String toString() #
Returns a string representation of this object.
String toString() => Primitives.objectToString(this);
void $dom_addEventListener(String type, EventListener listener, [bool useCapture]) #
@JSName('addEventListener')
@DomName('WebSocket.addEventListener')
@DocsEditable
void $dom_addEventListener(String type, EventListener listener, [bool useCapture]) native;
void $dom_removeEventListener(String type, EventListener listener, [bool useCapture]) #
@JSName('removeEventListener')
@DomName('WebSocket.removeEventListener')
@DocsEditable
void $dom_removeEventListener(String type, EventListener listener, [bool useCapture]) native;
This page includes content from the
Mozilla Foundation that is graciously
licensed under a
Creative Commons: Attribution-Sharealike license.
Mozilla has no other association with Dart or dartlang.org. We
encourage you to improve the web by
contributing to
The Mozilla Developer Network.