WebSocket server communicates with the connected clients via RFC 6455 protocol. The server requires each new connection and message to be singed with JWT token. In addition, it allows filtering messages broadcast to connected clients.
const {WebSocket, WebSocketMessage} = require('@aliceo2/web-ui');
WebSocket(HTTP_SERVER);
Where:
HTTP_SERVER
- instance of HTTP serverbind
broadcast
unfilteredBroadcast
shutdown
The WebSocket messages are represented as WebSocketMessage objects. The object consists of following fields:
A message can be constructed in following way:
WebSocketMessage(code = 200);
The message can be manipulated using setters:
setPayload
setBroadcast
setCommand
…and getters:
getPayload
getBroadcast
getProperty
getCode
getToken
In addition two methods for encoding and decoding messages to/from JSON are avaialble:
json
parse
Connecting clients may decide which broadcast messages they receive from server. This can be done by sending “filter” command (use setFilter
of frontends’ WebSocketClient).
The filter must be passed as stringified JavaScript function receiving WebSocketMessage object and returning true or false.
// Prepare http server
...
// Create instance of WebSocket server
const ws = new WebSocket(http);
// Print all messages with command 'print'
ws.bind('print', (message) => {
console.log(message.payload);
// ...and send back 'print-response'
return new WebSocketMessage().setCommand('print-response').setPayload('hi');
});