Spanish Total.js
English
Documentation For AI agents
Contents

WebSockets

The WebSocket object, its clients, WEBSOCKETCLIENT() and the WebSocket configuration.

.md GitHub
On this page

Methods, properties and events of WebSocket routes (ROUTE('SOCKET ...')), the WebSocket object, its clients, WEBSOCKETCLIENT() and the $ws* configuration keys. For an introduction with examples read the guide WebSockets.

API

method

ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])

Registers a WebSocket route.
ParameterTypeDescription
url String Method, path, flags and middleware
action Function Called with the WebSocket object
size? Number
  1. size of one message in bytes
Default: CONF.$wsmaxsize * 1024

Returns Route The registered route

The action runs once per URL, when the first client connects, with the WebSocket object as this and as the first argument. Prefix the method with + (authorized users only) or - (anonymous only). Flags: @json (default), @text, @binary (messages are Buffer objects and go out as binary frames, also when they are compressed) and @csrf. A client that the authorization refuses (it does not match + or -) is accepted and then closed with the code 4001. #name runs a middleware before the upgrade. The size limit is CONF.$wsmaxsize kB unless you pass size in bytes or <NMB in the URL. Returns the route.

Chat room
exports.install = function() {
	ROUTE('SOCKET /room/{name}/', room);
};

function room() {
	var self = this;
	self.on('message', function(client, message) {
		self.send(message);
	});
}
Authorized users, text messages, 1 MB
ROUTE('+SOCKET /console/ @text <1MB', terminal);
Binary messages
ROUTE('SOCKET /files/ @binary', function($) {
	$.on('message', function(client, buffer) {
		client.send(buffer); // a binary frame back
	});
});
config

CONF.$wsmaxsize

Default max. size of a WebSocket message in kB.

Returns Number

Default 256. A larger message closes the client with code 1009. A route can set its own size.

config file
$wsmaxsize		: 512
config

CONF.$wscompress

Allows permessage-deflate compression.

Returns Boolean

Default true. When the browser offers permessage-deflate, messages are compressed in both directions.

Disable compression
$wscompress	   : false
config

CONF.$wsencodedecode

Encodes and decodes all WebSocket messages with URI encoding.

Returns Boolean

Default false. With true, outgoing messages and close reasons go through encodeURIComponent() and incoming ones through decodeURIComponent(). The other side must do the same.

config file
$wsencodedecode   : true
config

CONF.$wsmaxlatency

  1. latency in ms before the ping check closes a client.

Returns Number

Default 2000. Three times a minute (15, 30 and 60 seconds into each minute) the framework pings all clients of all WebSocket routes and measures client.latency from the pong. Before each ping it checks the clients: a client that has not answered the previous ping, or whose latency is higher than CONF.$wsmaxlatency (2000 ms), is closed. This removes dead connections without your code.

config file
$wsmaxlatency	 : 5000
class

function() { var websocket = this; }

The object that groups all clients of one WebSocket URL.

Returns WebSocket

It is this in the action of a SOCKET route. One object exists per URL: a dynamic route has one per distinct URL. It is an event emitter (on, once, emit, off).

Events
function live() {
	var self = this;
	self.on('open', function(client) {});
	self.on('message', function(client, message) {});
	self.on('close', function(client) {});
}
property

websocket.online

The number of connected clients.

Returns Number

Count
self.on('open', function() {
	self.send({ type: 'online', count: self.online });
});
property

websocket.connections

The connected clients as an object { id: client }.

Returns Object

Iterate
for (var id in self.connections) {
	var client = self.connections[id];
}
property

websocket.params

The dynamic parameters of the URL.

Returns Object

Filled from the first client of the URL; all clients of the object share the same values.

Room name
ROUTE('SOCKET /room/{name}/', function() {
	var name = this.params.name;
});
property

websocket.url

The URL of the group in lower case.

Returns String

method

websocket.send(message, [comparer], [replacer], [params])

Sends a message to all clients, or to the clients chosen by a comparer.
ParameterTypeDescription
message Object|String|Buffer The message
comparer? Function function(client, message, params) returning a boolean
replacer? Function A JSON replacer
params? Object Passed to the comparer

Returns WebSocket The same object

The message is serialized with JSON.stringify() once (for @json and @text routes); on @binary routes pass a Buffer. comparer(client, message, params) returns true for the clients that receive it. replacer is passed to JSON.stringify(); when the third argument is not a function, it is used as params.

Everyone
self.send({ type: 'refresh' });
Only admins
self.send({ type: 'alert' }, function(client) {
	return client.user && client.user.isadmin;
});
method

websocket.find(fn)

Finds the first client for which fn(client) returns true.
ParameterTypeDescription
fn Function function(client) returning a boolean

Returns Controller The client, or undefined

By user
var client = self.find(function(client) {
	return client.user && client.user.id === id;
});
method

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

Closes all clients.
ParameterTypeDescription
code? Number The close code Default: 1000
message? String The close reason

Returns WebSocket

The WebSocket object stays, so new clients can connect.

Close everyone
self.close(4000, 'Maintenance');
method

websocket.destroy()

Closes all clients and removes the WebSocket object.

Emits destroy. The next client that connects to the URL runs the route action again and gets a new object.

Destroy
self.destroy();
method

websocket.autodestroy([callback])

Destroys the object 5 seconds after the last client leaves.
ParameterTypeDescription
callback? Function Called before the object is destroyed

Returns WebSocket

If a client connects in those 5 seconds, the object stays. Before destroying, every callback is called with the WebSocket object as this. Call it more times to add more callbacks.

Stop a timer
var timer = setInterval(function() {
	self.send({ ts: Date.now() });
}, 1000);

self.autodestroy(function() {
	clearInterval(timer);
});
method

websocket.encrypt([enable])

Encrypts and decrypts all messages of the group with CONF.secret_encryption.
ParameterTypeDescription
enable? Boolean Default: true

With no argument or true it enables encryption; false disables it. It does nothing while CONF.secret_encryption is empty.

Enable
function secure() {
	this.encrypt();
}
method

websocket.ping()

Pings all clients.

Returns WebSocket

Each pong sets client.latency. The framework calls it three times a minute (15, 30 and 60 seconds into each minute) for all WebSocket objects.

Ping now
self.ping();
method

websocket.error(err)

Logs an error with the URL of the WebSocket.
ParameterTypeDescription
err Error|String

A string is converted to an Error. The error goes to the framework error log.

Log
self.on('message', function(client, message) {
	if (!message.type)
		self.error('Missing type');
});
event

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

A client has connected.
ParameterTypeDescription
client Controller The new client
Welcome
self.on('open', function(client) {
	client.send({ type: 'welcome' });
});
event

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

A client has sent a message.
ParameterTypeDescription
client Controller
message Object|String|Buffer
size Number

On @json routes message is a parsed object; on @text routes a string; on @binary routes a Buffer. size is the size in bytes.

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

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

A client has disconnected.
ParameterTypeDescription
client Controller
code Number
message String

code and message are the close code and reason sent by the client, or the ones passed to close() when the server closes the connection.

Left
self.on('close', function(client) {
	self.send({ type: 'left', id: client.id });
});
event

websocket.on('error', function(err, client) {})

An error on a client socket.
ParameterTypeDescription
err Error
client Controller

Connection resets and broken pipes do not emit it; they close the client. An error while a message is compressed or decompressed (permessage-deflate) is emitted here with the client.

Log
self.on('error', function(err, client) {
	self.error(err);
});
event

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

The WebSocket object is being destroyed.

Emitted by destroy() and autodestroy().

Cleanup
self.on('destroy', function() {
	clearInterval(timer);
});
event

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

Any client of any WebSocket route has disconnected.
ParameterTypeDescription
websocket WebSocket
client Controller
Global log
ON('websocket_end', function(websocket, client) {
	console.log(websocket.url, client.ip);
});
class

client

One connected client of a WebSocket route.

Clients arrive in the events of the WebSocket object. They have the data of the upgrade request: id, ip, user, query, params, headers, url, uri, ua, mobile, robot, referrer, host, address, protocol, language, and req and socket. You can add your own properties. F.extend('controller', name, fn) adds a method to HTTP and WebSocket controllers.

Own data
self.on('open', function(client) {
	client.nick = client.query.nick || 'guest';
});
property

client.id

A unique identifier of the client.

Returns String

Also client.ID. It is the key in websocket.connections.

Send id
client.send({ id: client.id });
property

client.user

The user returned by the authorization delegate.

Returns Object

undefined for anonymous clients.

Greet
self.on('open', function(client) {
	client.send({ name: client.user ? client.user.name : 'guest' });
});
property

client.ip

The IP address of the client.

Returns String

The first address of X-Forwarded-For behind a proxy.

property

client.query

The query string of the WebSocket URL as an object.

Returns Object

Use it to pass data that browsers cannot send in headers, such as a token.

Token
// new WebSocket('ws://localhost:8000/live/?token=abc')
var token = client.query.token;
property

client.params

The dynamic parameters of the URL.

Returns Object

property

client.headers

The headers of the upgrade request, with lower-case names.

Returns Object

property

client.latency

The time in ms between the last ping and its pong.

Returns Number

Each ping resets it to null; the pong sets the measured time.

Show latency
self.on('message', function(client) {
	client.send({ latency: client.latency });
});
property

client.address

The full URL the client connected to.

Returns String

The protocol (http or https), the host and the path with the query string.

property

client.ua

A short name of the browser and system, parsed from User-Agent.

Returns String

client.mobile and client.robot are true for mobile devices and crawlers.

method

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

Sends a message to one client.
ParameterTypeDescription
message Object|String|Buffer
raw? Boolean Send a string without JSON serialization (@text routes) Default: false
replacer? Function A JSON replacer

On @json routes objects are serialized with JSON.stringify() and other values are sent as strings. On @text routes the message is serialized to JSON unless raw is true, which sends the string as it is. On @binary routes pass a Buffer. replacer is passed to JSON.stringify().

JSON
client.send({ type: 'pong' });
Plain text
client.send('OK', true);
method

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

Closes the connection with the client.
ParameterTypeDescription
code? Number The close code Default: 1000
message? String The close reason

The close frame is sent after 1 second and then the socket is destroyed.

Reject
self.on('open', function(client) {
	if (!client.query.token)
		client.close(4003, 'Forbidden');
});
method

client.ping()

Sends a ping to the client.

Returns Controller The same client

The pong sets client.latency.

method

client.cookie(name)

Reads a cookie of the upgrade request.
ParameterTypeDescription
name String

Returns String The decoded value, or an empty string

Session
var sid = client.cookie('sid');
method

client.hostname([path])

Returns the protocol and host of the request, with an optional path.
ParameterTypeDescription
path? String Appended to the host

Returns String For example https://example.com/path/

method

client.destroy()

Destroys the socket immediately, without a close frame.
method

WEBSOCKETCLIENT([callback])

Creates a WebSocket client that connects to another server.
ParameterTypeDescription
callback? Function function(client)

Returns WebSocketClient The client

callback(client) is called at once with the new client. Set the options, headers and events, 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('ws://127.0.0.1:8000/live/');
});
method

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

Opens the connection.
ParameterTypeDescription
url String|Object
protocol? String
origin? String

url is a ws:// or wss:// address, or an object { socket: '/path/to/unix.socket', path: '/live/' } for a Unix socket. protocol is sent as Sec-WebSocket-Protocol and origin as Sec-WebSocket-Origin. HTTP redirects (301, 302) are followed. The client emits open when the server accepts the connection.

Secure
client.connect('wss://example.com/live/');
property

wsclient.options

The options of the client.

Returns Object

Set them before connect(): type (json, text or binary, default json), compress (true), reconnect (delay in ms after the connection closes, 3000, 0 disables it), reconnectserver (true also reconnects when the connection cannot be opened or the server answers with an HTTP error), masking (false), encodedecode (false), encrypt (a key for encrypting messages), size (max. size in bytes of a decompressed message, 0 no limit), rejectunauthorized (false), timeout (TCP keep-alive delay in ms, 30000, 0 disables it), and key, cert, dhparam for TLS.

Text client
var client = WEBSOCKETCLIENT();
client.options.type = 'text';
client.options.reconnect = 0;
client.connect('ws://127.0.0.1:8000/terminal/');
property

wsclient.headers

Extra headers of the upgrade request.

Returns Object

Set them before connect().

Token
client.headers['x-token'] = 'secret';
method

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

Sends a message to the server.
ParameterTypeDescription
message Object|String|Buffer
raw? Boolean Send a prepared JSON string Default: false
replacer? Function A JSON replacer

Returns Boolean true when the message was written

With type json, the message is serialized with JSON.stringify() unless raw is true. With type text, objects are serialized and other values are sent as strings. With type binary, a non-Buffer value is converted to a Buffer. Returns false when the connection is closed.

Send
client.send({ type: 'subscribe', channel: 'news' });
method

wsclient.sendcustom(type, message)

Sends one message as text or binary, regardless of options.type.
ParameterTypeDescription
type String binary or text
message String|Buffer

Returns Boolean true when the message was written

type is 'binary' or any other value for text.

Binary
client.sendcustom('binary', Buffer.from([1, 2, 3]));
method

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

Closes the connection.
ParameterTypeDescription
code? Number Default: 1000
message? String|Boolean The close reason, or true

Returns WebSocketClient

It stops reconnecting. Pass true as message to close the connection and keep the automatic reconnection.

Close
client.close();
method

wsclient.destroy()

Destroys the connection and stops reconnecting.

Emits destroy.

Destroy
client.destroy();
method

wsclient.ping([timeout])

Sends a ping and waits for the pong.
ParameterTypeDescription
timeout? Number Time in ms Default: 3000

Returns WebSocketClient

The pong sets client.latency. Without a pong in timeout ms the client emits error with a Timeout error, closes the connection and reconnects when options.reconnect is set.

Keep checking
setInterval(function() {
	client.ping(5000);
}, 30000);
method

wsclient.api(schema, [data], [callback], [timeout])

Sends an API request over the connection and waits for the answer.
ParameterTypeDescription
schema String
data? Object
callback? Function function(err, response)
timeout? Number Time in ms Default: 5000

Returns Promise When no callback is given

Sends { TYPE: 'api', callbackid, data: { schema, data } } and resolves when the server answers with a message { TYPE: 'api', callbackid, data } (with error: true, data is the error). Without an answer in timeout ms (5000) the callback gets 408. Without a callback it returns a promise.

Promise
var response = await client.api('users_list', { page: 1 });
event

wsclient.on('message', function(message, size) {})

A message from the server.
ParameterTypeDescription
message Object|String|Buffer
size Number

A parsed object with type json, a string with text, a Buffer with binary.

event

wsclient.on('open', function() {})

The connection is open.

Also emitted after each reconnection.

event

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

The connection was closed.
ParameterTypeDescription
code Number
message String
event

wsclient.on('error', function(err) {})

A connection error, an unexpected HTTP response, an invalid server key or a ping timeout.
ParameterTypeDescription
err Error
Log
client.on('error', function(err) {
	console.log('WS error', err.message);
});
method

route.remove()

since 0.0.17 Removes a route registered with ROUTE().

For a SOCKET route it removes the route and destroys all its WebSocket objects, so every connected client is disconnected.

Remove
var route = ROUTE('SOCKET /live/', live);
route.remove();
Made in Europe