WebSockets
The SOCKET route, the WebSocket controller, the connected client and WEBSOCKETCLIENT().
On this page
A SOCKET route creates a WebSocket controller shared by all clients of a URL; each connection is a client object, and WEBSOCKETCLIENT() connects from the server to other WebSocket servers. The guide WebSockets explains how to use them with examples; this page is the exact reference.
API
method
ROUTE('SOCKET /url/', action, [flags], [length])
Declares a WebSocket route.
ROUTE('SOCKET /url/', action, [flags], [length])| Parameter | Type | Description |
|---|---|---|
url |
String |
SOCKET /path/, optionally with +/-, {params} and @apiname |
action |
Function |
Initializes the WebSocket controller |
flags |
Array |
Flags, origins, protocols, middleware, a length or an options object |
length |
Number |
Maximum message size in kB |
Returns FrameworkRoute The route instance
The URL starts with SOCKET (or WS, WSS). A + or - before it limits the route to signed-in or anonymous users. action runs once, when the first client connects to the URL, with the WebSocket controller as this and the dynamic URL parameters as arguments. length is the maximum size of one message in kB (default CONF.default_websocket_maxlength, 2). With @name in the URL and no action, the route processes the WebSocket API @name and destroys itself when the last client leaves.
The flags are described in the entry WebSocket route flags.
exports.install = function() {
ROUTE('SOCKET /chat/{room}/', chat, ['json'], 32);
};
function chat(room) {
var self = this;
self.autodestroy();
self.on('message', function(client, message) {
self.send({ room: room, body: message.body });
});
}
exports.install = function() {
ROUTE('API @chat -messages_list *Messages --> list');
ROUTE('SOCKET /chat/ @chat');
};
config
ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])
Flags that set the data type, access, origins and protocols of a WebSocket route.
ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])json(default): incoming messages are parsed as JSON (invalid JSON is ignored) and outgoing objects are serialized.text,plain: messages are strings; objects you send are serialized as JSON.binary: messages areBufferobjects.raw: turns offjsonandbinary(text mode).buffer: themessageevent always receives the rawBuffer.authorize,authorized,logged/unauthorize,unauthorized,unlogged: signed-in or anonymous users only.@role: a role flag; it makes the routeauthorize.http://...,https://...: allowed origins; the requestOriginmust contain one of them.#middleware,&middleware: middleware names.id:name: the route identifier.get,csrf,http,https,debug,release: standard route flags.- Any other word is a required sub-protocol. Every listed protocol must be in the client's
Sec-WebSocket-Protocolheader, otherwise the connection is closed with4001. - A number is the maximum message size in kB; an object is the middleware options.
ROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);
function upload() {
this.on('message', function(client, buffer) {
// buffer is a Buffer
});
}
// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');
ROUTE('SOCKET /rpc/', rpc, ['rpc']);
property
websocket.online
The number of connected clients.
websocket.onlineReturns Number
Updated whenever a client connects or disconnects.
function counter() {
var self = this;
self.on('open', function() {
self.send({ online: self.online });
});
}
property
websocket.connections
All connected clients by their id.
websocket.connectionsReturns Object
An object whose keys are client ids and values are client objects. websocket.keys holds the same ids as an array. websocket.id is the key of the controller in F.connections: the URL followed by # and the route flags.
var client = this.connections['15'];
property
websocket.url
The URL of the connection.
websocket.urlReturns String
The path the first client connected to, with a trailing slash.
property
websocket.params
The dynamic parameters of the URL.
websocket.paramsReturns Object
Each {name} of the route becomes a key. The same values arrive as arguments of the action.
ROUTE('SOCKET /rooms/{name}/', room);
function room(name) {
// name === this.params.name
}
property
websocket.repository
An object for your own data.
websocket.repositoryReturns Object
Created on first access and kept for the life of the controller.
function chat() {
var self = this;
self.repository.history = [];
self.on('message', function(client, message) {
self.repository.history.push(message);
});
}
method
websocket.on(name, callback)
Registers an event handler.
websocket.on(name, callback)| Parameter | Type | Description |
|---|---|---|
name |
String |
Event name |
callback |
Function |
Handler |
Returns WebSocket The controller
Events: open, close, message, error and destroy. this in the handler is the controller. once(name, fn) registers a handler for one call, removeListener(name, fn) and removeAllListeners([name]) remove handlers, and emit(name, [args...]) calls the handlers of your own events.
function chat() {
this.on('open', function(client) {});
this.on('message', function(client, message) {});
this.on('close', function(client, code, message) {});
}
method
websocket.send(message, [comparer], [replacer], [params])
Sends a message to all clients or to the clients you select.
websocket.send(message, [comparer], [replacer], [params])| Parameter | Type | Description |
|---|---|---|
message |
Object/String/Buffer |
The message |
comparer |
Function |
function(client, message, params) returns true to send |
replacer |
Function/Boolean |
JSON replacer |
params |
Object |
Value passed to comparer |
Returns WebSocket
In a json route the message is serialized once and sent to every client. comparer(client, message, params) returns true for the clients that receive the message. replacer is passed to JSON.stringify(); true uses the framework's JSON replacer. When the third argument is not a function, it is used as params.
self.on('message', function(client, message) {
self.send(message, function(c) {
return c !== client;
});
});
self.send({ type: 'refresh' }, function(client, message, params) {
return client.user && client.user.role === params.role;
}, { role: 'admin' });
method
websocket.find(fn)
Finds the first client that matches a function.
websocket.find(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(client) returns true for the wanted client |
Returns Object The client or undefined
Returns undefined when no client matches.
var client = this.find(function(client) {
return client.user && client.user.id === userid;
});
client && client.send({ type: 'notify' });
method
websocket.clients()
Returns all connected clients as an array.
websocket.clients()Returns Array
var users = this.clients().map(function(client) {
return client.user ? client.user.name : 'anonymous';
});
method
websocket.close([message], [code])
Closes all connected clients.
websocket.close([message], [code])| Parameter | Type | Description |
|---|---|---|
message |
String |
Close reason |
code |
Number |
Close code, default 1000 |
Returns WebSocket
Every client receives a close frame with code (default 1000) and message. The controller itself stays; use destroy() to remove it.
this.close('Server restart', 4000);
method
websocket.destroy()
Closes all clients and removes the controller.
websocket.destroy()Returns WebSocket
Emits destroy, removes the controller from F.connections and frees it. The next client of the URL creates a new controller.
method
websocket.autodestroy([callback])
Destroys the controller when no client is online.
websocket.autodestroy([callback])| Parameter | Type | Description |
|---|---|---|
callback |
Function |
Called before the controller is destroyed |
Returns WebSocket
When the last client disconnects and nobody connects within 5 seconds, callback is called (with the controller as this) and the controller is destroyed. Calling it again adds another callback.
function room() {
this.autodestroy(function() {
console.log('Destroyed', this.url);
});
}
method
websocket.ping()
Sends a ping to all clients.
websocket.ping()Returns WebSocket
The framework calls it on its own every CONF.default_interval_websocket_ping ms. The pong answer sets client.latency.
method
websocket.api(name)
since 0.0.44
Processes WebSocket API messages.
websocket.api(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
API name, with or without @ |
Returns WebSocket
Registers a message handler that runs API routes with the given @name for messages whose TYPE is api. The message data is { schema: 'operation/param', data: {} }; the answer is sent back to the client when the message has callbackid, with success: true and data, or error: true and the error items.
exports.install = function() {
ROUTE('API @chat -messages_list *Messages --> list');
ROUTE('SOCKET /chat/', chat);
};
function chat() {
this.api('@chat');
this.autodestroy();
}
method
websocket.encrypt([enable])
Encrypts messages with CONF.secret_encryption.
websocket.encrypt([enable])| Parameter | Type | Description |
|---|---|---|
enable |
Boolean |
Default true |
Returns WebSocket
When enabled and CONF.secret_encryption is set, outgoing text messages are encrypted and incoming ones decrypted. Without an argument it enables encryption.
event
websocket.on('open', function(client) {})
A client connected.
websocket.on('open', function(client) {})| Parameter | Type | Description |
|---|---|---|
client |
Object |
The new client |
Emitted after the client joined the controller, so this.online already counts it.
this.on('open', function(client) {
client.send({ type: 'welcome' });
});
event
websocket.on('message', function(client, message) {})
A client sent a message.
websocket.on('message', function(client, message) {})| Parameter | Type | Description |
|---|---|---|
client |
Object |
The sender |
message |
Object/String/Buffer |
The message |
message is an object in json routes, a string in text routes and a Buffer in binary or buffer routes.
this.on('message', function(client, message) {
client.send(message);
});
event
websocket.on('close', function(client, code, message) {})
A client disconnected.
websocket.on('close', function(client, code, message) {})| Parameter | Type | Description |
|---|---|---|
client |
Object |
The client |
code |
Number |
Close code |
message |
String |
Close reason |
code and message come from the close frame of the client, when it sent one.
event
websocket.on('error', function(err, client) {})
A socket error occurred.
websocket.on('error', function(err, client) {})| Parameter | Type | Description |
|---|---|---|
err |
Error |
The error |
client |
Object |
The client |
event
websocket.on('destroy', function() {})
The controller is being destroyed.
websocket.on('destroy', function() {})
property
client.id
The unique id of the connection.
client.idReturns String
A numeric string. It is also available as client.ID and is the key in websocket.connections. client.online is true while the connection is open, and client.controller (or client.container) is the WebSocket controller.
property
client.user
The user accepted by AUTH().
client.userReturns Object
You can also assign a value. client.session and client.sessionid hold the session values from the request.
var client = self.find(function(c) {
return c.user && c.user.id === message.to;
});
property
client.query
The query string of the connection URL.
client.queryReturns Object
The values are strings. client.get is an alias.
// new WebSocket('wss://example.com/live/?channel=sport')
this.on('open', function(client) {
client.channel = client.query.channel;
});
property
client.headers
The headers of the upgrade request.
client.headersReturns Object
Also available: client.ip, client.ua, client.url, client.uri, client.mobile, client.language and client.req. client.protocol is the array of sub-protocols from Sec-WebSocket-Protocol.
property
client.latency
The latency of the last ping in ms.
client.latencyReturns Number
Set when the client answers a ping. Clients without an answer or with a higher latency than CONF.default_websocket_maxlatency are closed.
method
client.send(message, [raw], [replacer])
Sends a message to this client.
client.send(message, [raw], [replacer])| Parameter | Type | Description |
|---|---|---|
message |
Object/String/Buffer |
The message |
raw |
Boolean |
Do not serialize (json routes) |
replacer |
Function/Boolean |
JSON replacer; true uses the framework's replacer |
Returns Object The client
In a json route objects are serialized; with raw set to true the message is sent as it is (a JSON string you already have). In a text route objects are serialized and other values converted to strings. In a binary route the message must be a Buffer. Nothing happens if the client is closed.
this.on('message', function(client, message) {
client.send({ ok: true, id: message.id });
});
method
client.close([message], [code])
Closes this connection.
client.close([message], [code])| Parameter | Type | Description |
|---|---|---|
message |
String |
Close reason |
code |
Number |
Close code, default 1000 |
Returns Object The client
Sends a close frame with code (default 1000) and message. The arguments can also be passed in the order (code, message).
client.close('Kicked', 4100);
method
client.cookie(name)
Reads a cookie of the upgrade request.
client.cookie(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Cookie name |
Returns String
var token = client.cookie('token');
method
client.hostname([path])
Returns the hostname with an optional path.
client.hostname([path])| Parameter | Type | Description |
|---|---|---|
path |
String |
Path to append |
Returns String
client.host() is an alias.
method
F.findConnection(path)
Finds a WebSocket controller by its id.
F.findConnection(path)| Parameter | Type | Description |
|---|---|---|
path |
String/RegExp |
Part of the id or a regular expression |
Returns WebSocket The controller or undefined
Returns the first controller whose id contains path (or matches a RegExp). Controllers are kept in F.connections.
function notify() {
var ws = F.findConnection('/notifications/');
ws && ws.send({ type: 'refresh' });
this.success();
}
method
F.findConnections([path])
Finds WebSocket controllers.
F.findConnections([path])| Parameter | Type | Description |
|---|---|---|
path |
String/RegExp |
Part of the id or a regular expression |
Returns Array
Without path it returns all controllers.
F.findConnections('/rooms/').forEach(function(ws) {
ws.send({ type: 'shutdown' });
});
event
ON('websocket_begin', function(controller, client) {})
A client joined a WebSocket controller.
ON('websocket_begin', function(controller, client) {})| Parameter | Type | Description |
|---|---|---|
controller |
WebSocket |
The controller |
client |
Object |
The client |
event
ON('websocket_end', function(controller, client) {})
A client left a WebSocket controller.
ON('websocket_end', function(controller, client) {})| Parameter | Type | Description |
|---|---|---|
controller |
WebSocket |
The controller |
client |
Object |
The client |
config
CONF.default_websocket_maxlength
The default maximum message size in kB.
CONF.default_websocket_maxlengthReturns Number
Default 2. A route overrides it with its length.
config
CONF.default_websocket_maxlatency
since 0.0.59
The maximum ping latency in ms.
CONF.default_websocket_maxlatencyReturns Number
Default 2000. Clients with a higher latency, or without a pong, are closed. 0 turns the pinger off. The ping runs every CONF.default_interval_websocket_ping ms (default 20000; values below 1000 use 20000).
config
CONF.allow_websocket
Enables WebSocket routes.
CONF.allow_websocketReturns Boolean
Default true. CONF.allow_websocket_compression (default true) allows permessage-deflate, and CONF.default_websocket_encodedecode (default false) turns on URI encoding of messages.
method
WEBSOCKETCLIENT([callback])
Creates a WebSocket client.
WEBSOCKETCLIENT([callback])| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function(client) |
Returns WebSocketClient
callback(client) is called at once with the new client (also as this). Set options, headers and events there, then call client.connect().
WEBSOCKETCLIENT(function(client) {
client.on('open', function() {
client.send({ type: 'hello' });
});
client.on('message', function(message) {
console.log(message);
});
client.connect('wss://example.com/chat/');
});
property
websocketclient.options
Options of the client.
websocketclient.optionsReturns Object
type('json'):json,text,binaryorbuffer.compress(true): asks forpermessage-deflate.reconnect(3000): ms before reconnecting after a closed connection;0disables it.reconnectserver(false): also reconnect after a connection error or an unexpected HTTP response.masking(false): masks outgoing frames.encodedecode(false): URI encoding of messages.encrypt: a secret to encrypt and decrypt text messages.length: maximum size of a decompressed message in bytes.rejectunauthorized(false): rejects invalid TLS certificates.key,cert,dhparam: TLS options.
WEBSOCKETCLIENT(function(client) {
client.options.type = 'text';
client.options.reconnect = 10000;
client.connect('ws://127.0.0.1:8000/log/');
});
property
websocketclient.headers
Extra headers of the upgrade request.
websocketclient.headersReturns Object
websocketclient.cookies is an object of cookies sent in the Cookie header.
client.headers['x-token'] = 'secret';
client.cookies.session = 'abc';
property
websocketclient.closed
true when the client is not connected.
websocketclient.closedReturns Boolean
websocketclient.reconnect counts the reconnections.
property
websocketclient.latency
since 0.0.44
The latency of the last ping in ms.
websocketclient.latencyReturns Number
Set when the server answers ping().
method
websocketclient.connect(url, [protocol], [origin])
Opens the connection.
websocketclient.connect(url, [protocol], [origin])| Parameter | Type | Description |
|---|---|---|
url |
String/Object |
Server URL |
protocol |
String |
Sub-protocol |
origin |
String |
Origin |
url starts with ws:// or wss://. It can also be an object { socket: '/path/to/unix.socket', path: '/chat/' }. protocol is sent in Sec-WebSocket-Protocol and origin in Sec-WebSocket-Origin. The connection starts on the next tick.
client.connect('wss://example.com/rpc/', 'rpc');
method
websocketclient.send(message, [raw], [replacer])
Sends a message.
websocketclient.send(message, [raw], [replacer])| Parameter | Type | Description |
|---|---|---|
message |
Object/String/Buffer |
The message |
raw |
Boolean |
Do not serialize (json) |
replacer |
Function/Boolean |
JSON replacer |
Returns Boolean true when sent
With type: 'json' objects are serialized (unless raw is true). With text objects are serialized and other values converted to strings. With binary or buffer a non-Buffer message is converted to a Buffer. Returns false when the client is closed.
if (!client.send({ type: 'ping' }))
console.log('Not connected');
method
websocketclient.close([message], [code])
Closes the connection.
websocketclient.close([message], [code])| Parameter | Type | Description |
|---|---|---|
message |
String/Boolean |
Close reason, or true to reconnect |
code |
Number |
Close code, default 1000 |
Returns WebSocketClient
Sends a close frame with code (default 1000). It also stops reconnecting, unless message is true: then the connection closes and the client reconnects. The arguments can be passed as (code, message).
// Close and connect again after options.reconnect ms
client.close(true);
method
websocketclient.destroy()
since 0.0.42
Frees the client and stops reconnecting.
websocketclient.destroy()Emits destroy and removes all event handlers.
method
websocketclient.ping([timeout])
since 0.0.44
Sends a ping to the server.
websocketclient.ping([timeout])| Parameter | Type | Description |
|---|---|---|
timeout |
Number |
Default 3000 ms |
Returns WebSocketClient
If no pong arrives within timeout ms (default 3000), the client emits error with 'Timeout' and closes. The pong sets latency.
setInterval(function() {
client.ping(5000);
}, 30000);
method
websocketclient.api([schema], [data], [callback], [timeout])
since 0.0.44
Calls the WebSocket API of a Total.js server.
websocketclient.api([schema], [data], [callback], [timeout])| Parameter | Type | Description |
|---|---|---|
schema |
String |
Operation, e.g. 'messages_read/123' |
data |
Object |
Payload |
callback |
Function |
function(err, response) |
timeout |
Number |
Default 5000 ms |
Returns WebSocketClient
Sends { TYPE: 'api', data: { schema, data } }. callback(err, response) gets the answer; err is 408 after timeout ms (default 5000). Without schema it only registers the handler for answers.
client.api('messages_list', { page: 1 }, function(err, response) {
if (err)
console.log(err);
else
console.log(response);
});
method
websocketclient.on(name, callback)
Registers an event handler.
websocketclient.on(name, callback)| Parameter | Type | Description |
|---|---|---|
name |
String |
Event name |
callback |
Function |
Handler |
Returns WebSocketClient
Events: open(), message(data), close(code, message), error(err) and destroy(). once(), removeListener(), removeAllListeners() and emit() work as in the controller.
client.on('open', function() {});
client.on('message', function(data) {});
client.on('close', function(code, message) {});
client.on('error', function(err) {});
property
client.session
The session of the connection.
client.sessionReturns Object
The session set by your AUTH() delegate for the upgrade request. client.sessionid is its id. It can be set.
function socket() {
this.on('open', function(client) {
console.log(client.sessionid, client.session);
});
}
method
client.ping()
Sends a ping frame to this client.
client.ping()Returns Object The client.
The answer of the client updates client.latency. websocket.ping() pings all clients.
function socket() {
this.on('open', function(client) {
client.ping();
});
}
property
websocketclient.url
The URL of the last connect().
websocketclient.urlReturns String
websocketclient.protocol and websocketclient.origin keep the other arguments of connect().
WEBSOCKETCLIENT(function(client) {
client.connect('wss://example.com/live/');
client.on('open', function() {
console.log('Connected to', client.url);
});
});