Class: WSSocket

WSSocket

Provides methods and properties for creating a web socket server.

This allows another WAT device or a browser with WebSocket support to connect. Once connected, a two-way channel is created for messages to be sent to or from the client. Multiple clients can connect simultaneously. The currently connected clients are available in clients. When a new client connects, the newClient event is emitted.

Some browsers may automatically disconnect an open WebSocket that has not had activity for a period of time. If suitable logic has been added to the client code to reconnect when a disconnect happens, that should cover this case as well. A client can also prevent timeouts by ensuring that something is always sent more frequently than the timeout (e.g. a heartbeat message).

A WSSocket is created using createSocket.


Examples

Server (WATbox)

// start before the client
var $ws = $wat.load('ws')[0];
// for brevity, this example does not deal with errors and edge cases
var myWSSocket = $ws.createSocket(8500, 'socketName');

myWSSocket.newClient.connect(newClient);

function newClient(client) {
  //send message
  client.send("message for client")
  client.messageReceived.connect(clientMessageReceived);
}

function clientMessageReceived(message) {
   console.log("message received: " + message);
}

Client (WATbox or modern browser)

// make sure the server is already started
// change 'example_server' for DNS entry or IP address of server
var socket = new WebSocket('ws://example_server:8500');

// for brevity, this example does not deal with error and edge cases
// check the WebSocket specification for more events
socket.addEventListener('message', function (event) {
    console.log('Message from server:', event.data);
    socket.send('hello from client');
});

Members


<readonly> clients :Array.<ws.WSClient>

An array of clients connected to the web socket.

Type:
Since:
  • 0.1 (WAT 2.0)

<readonly> path :string

The path that the server is running on. Not applicable if the socket was started on a port.

Type:
  • string
Since:
  • 1.1 (WAT 2.3)

<readonly> port :number

The port that the server is running on. Not applicable if the socket was started on a path.

Type:
  • number
Since:
  • 0.1 (WAT 2.0)

Events


newClient

Emitted when a new client connects to the web socket.

Parameters:
Name Type Description
client ws.WSClient

New client

Since:
  • 0.1 (WAT 2.0)