Spanish Total.js
English
Documentation For AI agents
Contents

WebSockets

Declare WebSocket routes, handle clients and messages in the WebSocket controller, and connect to WebSocket servers with WEBSOCKETCLIENT().

.md GitHub
On this page

A WebSocket route keeps a connection open between the browser and the server. In Total.js you declare it with ROUTE() and the SOCKET method. The action of the route does not answer a request: it runs once, when the first client connects, and its this is a WebSocket controller shared by every client of that route.

exports.install = function() {
    ROUTE('SOCKET /chat/', chat);
};

function chat() {

    var self = this;

    self.on('open', function(client) {
        client.send({ type: 'welcome', id: client.id });
    });

    self.on('message', function(client, message) {
        // Send the message to everybody
        self.send({ type: 'message', from: client.id, body: message.body });
    });

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

The full list of properties and methods is in the reference of WebSockets.

Declaring a route

ROUTE('SOCKET /path/', action, [flags], [length]) registers the route. WS and WSS are accepted as aliases of SOCKET. A + before the method allows only signed-in users and a - only anonymous users, as in other routes:

exports.install = function() {
    ROUTE('+SOCKET /notifications/', notifications);
    ROUTE('SOCKET /live/{room}/', live, ['json'], 64);
};

function live(room) {
    // room === this.params.room
}

Dynamic parts of the URL arrive as arguments of the action and in this.params. The length argument (or a number in the flags) is the maximum size of one message in kB. The default comes from CONF.default_websocket_maxlength (2 kB). A bigger frame closes the connection with code 1009.

Flags

FlagMeaning
jsonMessages are JSON (the default). Incoming messages are parsed, outgoing objects are serialized.
text or plainMessages are strings.
binaryMessages are binary; message receives a Buffer.
rawTurns off json and binary; messages are handled as text.
bufferThe message event always receives the raw Buffer.
authorize, loggedOnly signed-in users (the same as +).
unauthorize, unloggedOnly anonymous users (the same as -).
@roleMarks a role; the route also becomes authorize.
http://…, https://…Allowed origins. The Origin header must contain one of them.
#name or &nameMiddleware run before the connection is accepted.
id:nameAn identifier of the route.
debug, release, http, httpsLimit the route to a mode or a protocol.
any other wordA required sub-protocol: the client must send it in Sec-WebSocket-Protocol.
a numberThe maximum message size in kB.
an objectOptions passed to the middleware.
ROUTE('SOCKET /api/', api, ['json', 'https://www.example.com', 'chat'], 128);

This route accepts only clients from https://www.example.com that ask for the chat sub-protocol, and messages up to 128 kB.

How connections are grouped

Every route has one controller per URL. The first client creates it and runs the action; later clients on the same URL join the existing controller, and the action is not called again. That is why the action registers events instead of answering.

function counter() {
    var self = this;
    self.on('open', function() {
        self.send({ online: self.online });
    });
    self.on('close', function() {
        self.send({ online: self.online });
    });
}

Without more code the controller stays in memory after the last client leaves. Call this.autodestroy() to destroy it 5 seconds after the last client disconnects; the next client creates a new one and the action runs again:

function room() {
    var self = this;
    self.autodestroy(function() {
        console.log('Room closed:', self.url);
    });
}

Receiving and sending

With the default json flag, message receives a parsed object; invalid JSON is ignored. client.send(obj) sends to one client and this.send(obj) sends to all clients of the controller. The second argument of this.send() filters the receivers:

function chat() {
    var self = this;
    self.on('message', function(client, message) {

        // Everybody except the sender
        self.send(message, function(c) {
            return c !== client;
        });

        // Only users of one company
        self.send(message, function(c, msg, params) {
            return c.user && c.user.companyid === params.companyid;
        }, { companyid: client.user.companyid });
    });
}

this.find(fn) returns the first client for which fn returns true, and this.clients() returns all clients as an array. this.online is the number of connected clients and this.connections maps client ids to clients.

The client of a connection

Every connected client has id, ip, query, headers, url, ua, user, session, language, mobile and protocol. user is the value accepted by your AUTH() delegate:

// definitions/auth.js
AUTH(function($) {
    // $.websocket is true for WebSocket connections
    var token = $.query.token || $.cookie('token');
    if (token === 'secret')
        $.success({ id: 1, name: 'Peter' });
    else
        $.invalid();
});

// controllers/default.js
exports.install = function() {
    ROUTE('+SOCKET /private/', privatechannel);
};

function privatechannel() {
    this.on('open', function(client) {
        client.send({ hello: client.user.name });
    });
}

A client that fails authorization is closed with code 4001, a URL without a route with 4004, and invalid URL parameters with 4000.

client.close([message], [code]) closes one client and this.close([message], [code]) closes all of them. The default code is 1000.

Ping and stale connections

The framework pings every connected client every CONF.default_interval_websocket_ping milliseconds (default 20000). The answer sets client.latency. A client that did not answer, or whose latency is higher than CONF.default_websocket_maxlatency (default 2000 ms), is closed at the next round. Set default_websocket_maxlatency to 0 to turn the pinger off.

WebSocket API

A route can process API routes over the socket. Declare the API with @name and use the same name in the socket route:

exports.install = function() {
    ROUTE('API @chat -messages_list   *Messages --> list');
    ROUTE('API @chat +messages_create *Messages --> create');
    ROUTE('SOCKET /chat/ @chat');
};

A SOCKET route with @name and no action calls this.api('@name') and this.autodestroy() for you. The client sends { TYPE: 'api', callbackid: '1', data: { schema: 'messages_list', data: {} } } and gets the same object back with success: true and data, or error: true and the errors.

Connecting from the server

WEBSOCKETCLIENT() creates a WebSocket client, for example to connect one Total.js app to another:

WEBSOCKETCLIENT(function(client) {

    client.options.reconnect = 5000;
    client.headers['x-token'] = 'secret';

    client.on('open', function() {
        client.send({ type: 'hello' });
    });

    client.on('message', function(message) {
        console.log(message);
    });

    client.on('close', function(code, message) {
        console.log('Closed', code, message);
    });

    client.connect('ws://127.0.0.1:8000/chat/');
});

client.options.type is json by default; use text, binary or buffer for other data. The client reconnects 3 seconds after the connection is lost (options.reconnect); client.close() stops reconnecting and client.destroy() frees the client. client.api(schema, data, callback) calls the WebSocket API of the server:

client.api('messages_list', { page: 1 }, function(err, response) {
    console.log(err, response);
});

Configuration

KeyDefaultMeaning
allow_websockettrueEnables WebSocket routes.
allow_websocket_compressiontrueAllows permessage-deflate compression.
default_websocket_maxlength2Maximum message size in kB.
default_websocket_maxlatency2000Maximum ping latency in ms; 0 disables the pinger.
default_interval_websocket_ping20000Interval of the ping in ms.
default_websocket_encodedecodefalseEncodes messages with encodeURIComponent() and decodes them.
Made in Europe