WebSocket class

Use the WebSocket interface to connect to a WebSocket, and to send and receive data on that WebSocket.

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.onMessage.listen((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.

Annotations
  • DocsEditable()
  • DomName('WebSocket')
  • SupportedBrowser(SupportedBrowser.CHROME)
  • SupportedBrowser(SupportedBrowser.FIREFOX)
  • SupportedBrowser(SupportedBrowser.IE, '10')
  • SupportedBrowser(SupportedBrowser.SAFARI)
  • Unstable()
Extends

Constructors

WebSocket(String url, [protocol_OR_protocols])

Constants

closeEvent = const EventStreamProvider<CloseEvent>('close')
Static factory designed to expose close events to event handlers that are not necessarily instances of WebSocket.
errorEvent = const EventStreamProvider<Event>('error')
Static factory designed to expose error events to event handlers that are not necessarily instances of WebSocket.
messageEvent = const EventStreamProvider<MessageEvent>('message')
Static factory designed to expose message events to event handlers that are not necessarily instances of WebSocket.
openEvent = const EventStreamProvider<Event>('open')
Static factory designed to expose open events to event handlers that are not necessarily instances of WebSocket.
CLOSED = 3
CLOSING = 2
CONNECTING = 0
OPEN = 1

Static Properties

supported bool
read-only

Instance Properties

binaryType String
read / write
bufferedAmount int
read-only
extensions String
read-only
protocol String
read-only
readyState int
read-only
url String
read-only
onClose Stream<CloseEvent>
read-only
onError Stream<Event>
read-only
onMessage Stream<MessageEvent>
read-only
onOpen Stream<Event>
read-only
on Events Inherited
read-only

Instance Methods

close([int code, String reason]) → void
send(data) → void
sendBlob(Blob data) → void
sendByteBuffer(ByteBuffer data) → void
sendString(String data) → void
sendTypedData(TypedData data) → void
addEventListener(String type, dynamic listener(Event event), [bool useCapture]) → void Inherited
removeEventListener(String type, dynamic listener(Event event), [bool useCapture]) → void Inherited
dispatchEvent(Event event) → bool Inherited