WebSocket

WebSocket library for a JavaScript Plugin

Remarks

Here's an example that connects to the WebSocket Echo server hosted by websocket.org

All echo responses are written to the Log window.

Example

plugin.Name = "WebSocketExample";
plugin.OnChangeRequest = onChangeRequest;
plugin.OnConnect = onConnect;
plugin.OnDisconnect = onDisconnect;
plugin.OnPoll = onPoll;
plugin.OnSynchronizeDevices = onSynchronizeDevices;
plugin.PollingInterval = 250;
var websocket = new WebSocket();
var echoDeviceId = "echo-device";
function onChangeRequest(device, attribute, value) {
switch (attribute) {
case "Echo":
websocket.send(value);
break;
default:
return;
}
}
function onConnect() {
websocket.connect("ws://echo.websocket.org");
}
function onDisconnect() {
websocket.close();
}
function onPoll() {
var data = websocket.receive();
console.log("message received: " + data);
var echoDevice = plugin.Devices[echoDeviceId];
echoDevice.Echo = data;
}
function onSynchronizeDevices() {
var echoDevice = new Device();
echoDevice.Id = echoDeviceId;
echoDevice.DisplayName = "Echo Device";
echoDevice.Capabilities = [];
echoDevice.Attributes = ["Echo"];
plugin.Devices[echoDevice.Id] = echoDevice;
}

Methods

connect

Connect to a WebSocket server.

connect(url, [options])

  • url : The URI of the WebSocket server to connect to.
  • options
    • timeout : Time, in milliseconds, to wait before timing out. The default is 0 which waits indefinitely.

close

Close connection to the WebSocket server.

close([closeCode], [reason])

  • closeCode : The WebSocket closing code. Defaults to 1005 (Empty).
  • reason : The reason for closing the connection. Defaults to empty string.

receive

Receives data from the WebSocket server.

receive([options])

  • options
    • encoding : The encoding of received text data. The default is UTF8.
    • timeout : Time, in milliseconds, to wait before timing out. The default is 0 which waits indefinitely.

Returns either a message string or bytes depending on the type of the message received.

send

Sends data to the WebSocket server.

send(data, [options])

  • data : For a Text message, the data should be a string. For a Binary message, the data should be a byte array.
  • options
    • encoding : The string encoding for a Text message. The default is UTF8.
    • timeout : Time, in milliseconds, to wait before timing out. The default is 0 which waits indefinitely.