Spanish Total.js
English
Documentation For AI agents
Contents

WebSockets

The SOCKET route, the WebSocket controller, the connected client and WEBSOCKETCLIENT().

.md GitHub
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.
ParameterTypeDescription
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.

Chat route
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 });
	});
}
WebSocket API without an action
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.
  • 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 are Buffer objects.
  • raw: turns off json and binary (text mode).
  • buffer: the message event always receives the raw Buffer.
  • authorize, authorized, logged / unauthorize, unauthorized, unlogged: signed-in or anonymous users only.
  • @role: a role flag; it makes the route authorize.
  • http://..., https://...: allowed origins; the request Origin must 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-Protocol header, otherwise the connection is closed with 4001.
  • A number is the maximum message size in kB; an object is the middleware options.
Binary route for one origin
ROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);

function upload() {
	this.on('message', function(client, buffer) {
		// buffer is a Buffer
	});
}
Required sub-protocol
// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');
ROUTE('SOCKET /rpc/', rpc, ['rpc']);
property

websocket.online

The number of connected clients.

Returns Number

Updated whenever a client connects or disconnects.

Broadcast the count
function counter() {
	var self = this;
	self.on('open', function() {
		self.send({ online: self.online });
	});
}
property

websocket.connections

All connected clients by their id.

Returns 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.

Read a client
var client = this.connections['15'];
property

websocket.url

The URL of the connection.

Returns String

The path the first client connected to, with a trailing slash.

property

websocket.params

The dynamic parameters of the URL.

Returns Object

Each {name} of the route becomes a key. The same values arrive as arguments of the action.

Room name
ROUTE('SOCKET /rooms/{name}/', room);

function room(name) {
	// name === this.params.name
}
property

websocket.repository

An object for your own data.

Returns Object

Created on first access and kept for the life of the controller.

Keep history
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.
ParameterTypeDescription
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.

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.
ParameterTypeDescription
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.

Everybody except the sender
self.on('message', function(client, message) {
	self.send(message, function(c) {
		return c !== client;
	});
});
With params
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.
ParameterTypeDescription
fn Function function(client) returns true for the wanted client

Returns Object The client or undefined

Returns undefined when no client matches.

Find a user
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.

Returns Array

List users
var users = this.clients().map(function(client) {
	return client.user ? client.user.name : 'anonymous';
});
method

websocket.close([message], [code])

Closes all connected clients.
ParameterTypeDescription
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.

Close everybody
this.close('Server restart', 4000);
method

websocket.destroy()

Closes all clients and removes the controller.

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.
ParameterTypeDescription
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.

Auto destroy
function room() {
	this.autodestroy(function() {
		console.log('Destroyed', this.url);
	});
}
method

websocket.ping()

Sends a ping to all clients.

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.
ParameterTypeDescription
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.

Process an API
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.
ParameterTypeDescription
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.
ParameterTypeDescription
client Object The new client

Emitted after the client joined the controller, so this.online already counts it.

Welcome
this.on('open', function(client) {
	client.send({ type: 'welcome' });
});
event

websocket.on('message', function(client, message) {})

A client sent a message.
ParameterTypeDescription
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.

Echo
this.on('message', function(client, message) {
	client.send(message);
});
event

websocket.on('close', function(client, code, message) {})

A client disconnected.
ParameterTypeDescription
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.
ParameterTypeDescription
err Error The error
client Object The client
event

websocket.on('destroy', function() {})

The controller is being destroyed.
property

client.id

The unique id of the connection.

Returns 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().

Returns Object

You can also assign a value. client.session and client.sessionid hold the session values from the request.

Private message
var client = self.find(function(c) {
	return c.user && c.user.id === message.to;
});
property

client.query

The query string of the connection URL.

Returns Object

The values are strings. client.get is an alias.

Token in the URL
// 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.

Returns 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.

Returns 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.
ParameterTypeDescription
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.

Reply
this.on('message', function(client, message) {
	client.send({ ok: true, id: message.id });
});
method

client.close([message], [code])

Closes this connection.
ParameterTypeDescription
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).

Kick a client
client.close('Kicked', 4100);
method

client.cookie(name)

Reads a cookie of the upgrade request.
ParameterTypeDescription
name String Cookie name

Returns String

Read a cookie
var token = client.cookie('token');
method

client.hostname([path])

Returns the hostname with an optional path.
ParameterTypeDescription
path String Path to append

Returns String

client.host() is an alias.

method

F.findConnection(path)

Finds a WebSocket controller by its id.
ParameterTypeDescription
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.

Send from an HTTP route
function notify() {
	var ws = F.findConnection('/notifications/');
	ws && ws.send({ type: 'refresh' });
	this.success();
}
method

F.findConnections([path])

Finds WebSocket controllers.
ParameterTypeDescription
path String/RegExp Part of the id or a regular expression

Returns Array

Without path it returns all controllers.

All rooms
F.findConnections('/rooms/').forEach(function(ws) {
	ws.send({ type: 'shutdown' });
});
event

ON('websocket_begin', function(controller, client) {})

A client joined a WebSocket controller.
ParameterTypeDescription
controller WebSocket The controller
client Object The client
event

ON('websocket_end', function(controller, client) {})

A client left a WebSocket controller.
ParameterTypeDescription
controller WebSocket The controller
client Object The client
config

CONF.default_websocket_maxlength

The default maximum message size in kB.

Returns 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.

Returns 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.

Returns 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.
ParameterTypeDescription
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().

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.

Returns Object

  • type ('json'): json, text, binary or buffer.
  • compress (true): asks for permessage-deflate.
  • reconnect (3000): ms before reconnecting after a closed connection; 0 disables 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.
Text client
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.

Returns Object

websocketclient.cookies is an object of cookies sent in the Cookie header.

Token
client.headers['x-token'] = 'secret';
client.cookies.session = 'abc';
property

websocketclient.closed

true when the client is not connected.

Returns Boolean

websocketclient.reconnect counts the reconnections.

property

websocketclient.latency

since 0.0.44 The latency of the last ping in ms.

Returns Number

Set when the server answers ping().

method

websocketclient.connect(url, [protocol], [origin])

Opens the connection.
ParameterTypeDescription
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.

With a protocol
client.connect('wss://example.com/rpc/', 'rpc');
method

websocketclient.send(message, [raw], [replacer])

Sends a message.
ParameterTypeDescription
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.

Send
if (!client.send({ type: 'ping' }))
	console.log('Not connected');
method

websocketclient.close([message], [code])

Closes the connection.
ParameterTypeDescription
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).

Reconnect
// Close and connect again after options.reconnect ms
client.close(true);
method

websocketclient.destroy()

since 0.0.42 Frees the client and stops reconnecting.

Emits destroy and removes all event handlers.

method

websocketclient.ping([timeout])

since 0.0.44 Sends a ping to the server.
ParameterTypeDescription
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.

Measure 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.
ParameterTypeDescription
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.

Call an operation
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.
ParameterTypeDescription
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.

Events
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.

Returns Object

The session set by your AUTH() delegate for the upgrade request. client.sessionid is its id. It can be set.

Example
function socket() {
	this.on('open', function(client) {
		console.log(client.sessionid, client.session);
	});
}
method

client.ping()

Sends a ping frame to this client.

Returns Object The client.

The answer of the client updates client.latency. websocket.ping() pings all clients.

Ping one client
function socket() {
	this.on('open', function(client) {
		client.ping();
	});
}
property

websocketclient.url

The URL of the last connect().

Returns String

websocketclient.protocol and websocketclient.origin keep the other arguments of connect().

Example
WEBSOCKETCLIENT(function(client) {
	client.connect('wss://example.com/live/');
	client.on('open', function() {
		console.log('Connected to', client.url);
	});
});
Made in Europe