Table Of Contents

Previous topic

9.30. The NetworkDevice Object

Next topic

9.32. The InputDevice Object

This Page

9.31. The WebSocket Object

A WebSocket object that follows the browser standard. For detailed information about the API please read the WebSocket specification.

9.31.1. Constructor

A WebSocket object can be constructed with NetworkDevice.createWebSocket.

9.31.2. Methods

9.31.2.1. send

Summary

Sends a text message.

Syntax

var message = "Hello World!";
websocket.send(message);
message
The message string to be send. You can serialize JavaScript objects to strings by using JSON.stringify.

9.31.2.2. close

Summary

Closes the connection and prepares the WebSocket to be released.

Syntax

websocket.close();

9.31.3. Properties

9.31.3.1. readyState

Summary

The state of the WebSocket connection. All the possible values are properties on the WebSocket object:

  • CONNECTING
  • OPEN
  • CLOSING
  • CLOSED

Syntax

if (websocket.readyState === websocket.OPEN)
{
    // Connection is ready for sending data
}
else if (websocket.readyState === websocket.CLOSED)
{
    // Connection was closed
}

Note

Read Only

9.31.3.2. onopen

Summary

The callback that will be executed when the connection is established successfully.

Syntax

websocket.onopen = function connectionOpened() {
    websocket.send("Hello World!");
};

9.31.3.3. onmessage

Summary

The callback that will be executed when a new message arrives.

Syntax

websocket.onmessage = function messageReceived(message) {
    window.alert("Message from server: " + message.data);
};

9.31.3.4. onerror

Summary

The callback that will be executed when the connection breaks.

Syntax

websocket.onerror = function connectionError() {
    window.alert("Connection broken!");
    websocket.onopen = null;
    websocket.onerror = null;
    websocket.onclose = null;
    websocket.onmessage = null;
    websocket = null;
};

9.31.3.5. onclose

Summary

The callback that will be executed when the connection is closed.

Syntax

websocket.onclose = function connectionOpened() {
    window.alert("Connection closed!");
    websocket.onopen = null;
    websocket.onerror = null;
    websocket.onclose = null;
    websocket.onmessage = null;
    websocket = null;
};