Dart API Referencedart:htmlWebSocket

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 int CLOSED #

The connection is closed or couldn't be opened.
static const int CLOSED = 3

const EventStreamProvider<CloseEvent> closeEvent #

static const EventStreamProvider<CloseEvent> closeEvent = const EventStreamProvider<CloseEvent>('close')

const int CLOSING #

The connection is in the process of closing.
static const int CLOSING = 2

const int CONNECTING #

The connection is not yet open.
static const int CONNECTING = 0

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 int OPEN #

The connection is open and ready to communicate.
static const int OPEN = 1

const EventStreamProvider<Event> openEvent #

static const EventStreamProvider<Event> openEvent = const EventStreamProvider<Event>('open')

final bool supported #

Checks if this type is supported on the current platform.

static bool get supported => JS('bool', 'typeof window.WebSocket != "undefined"');

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 #

A string indicating the type of binary data being transmitted by the connection. This should be either "blob" if DOM Blob  objects are being used or "arraybuffer" if ArrayBuffer objects are being used.
String binaryType

final int bufferedAmount #

The number of bytes of data that have been queued using calls to but not yet transmitted to the network. This value does not reset to zero when the connection is closed; if you keep calling , this will continue to climb. Read only.
final int bufferedAmount

final String extensions #

The extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection.
final String extensions

final int hashCode #

inherited from Interceptor

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.

docs inherited from Object
int get hashCode => Primitives.objectHashCode(this);

final Events on #

inherited from EventTarget

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 #

An event listener to be called when the WebSocket connection's 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 #

An event listener to be called when an error occurs. This is a simple event named "error".
@DomName('WebSocket.onerror')
@DocsEditable
Stream<Event> get onError => errorEvent.forTarget(this);

final Stream<MessageEvent> onMessage #

An event listener to be called when a message is received from the server. The listener receives a MessageEvent named "message".
@DomName('WebSocket.onmessage')
@DocsEditable
Stream<MessageEvent> get onMessage => messageEvent.forTarget(this);

final Stream<Event> onOpen #

An event listener to be called when the WebSocket connection's 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 #

A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object.
final String protocol

final int readyState #

The current state of the connection; this is one of the Ready state constants. Read only.
final int readyState

final Type runtimeType #

inherited from Interceptor

A representation of the runtime type of the object.

docs inherited from Object
Type get runtimeType => getRuntimeType(this);

final String url #

The URL as resolved by the constructor. This is always an absolute URL. Read only.
final String url

final String Url #

final String Url

Operators

bool operator ==(other) #

inherited from Interceptor

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.

docs inherited from Object
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
code Optional
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 CloseEvent page for permitted values.
reason Optional
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 code was specified.
SYNTAX_ERR
The reason string 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) #

inherited from Interceptor

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.

docs inherited from Object
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 6.0 note
(Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3)

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() #

inherited from Interceptor

Returns a string representation of this object.

docs inherited from 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.