Spanish Total.js
English
Documentation For AI agents
Contents

WebSockets

Real-time connections with SOCKET routes, the WebSocket object and its clients, compression, ping and the WebSocket client.

.md GitHub
On this page

A WebSocket route keeps a connection open between the browser (or another server) and your application, so both sides can send messages at any time. Total.js handles the handshake, the frames, compression, ping and JSON for you.

A WebSocket route

Declare it with the SOCKET method. The action runs with a WebSocket object as this (and as the first argument). You attach events to it; each connected browser arrives as a client.

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) {
        // message is already parsed from JSON
        self.send({ type: 'message', from: client.id, body: message.body });
    });

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

In the browser:

var ws = new WebSocket('ws://localhost:8000/chat/');
ws.onmessage = function(e) {
    var msg = JSON.parse(e.data);
};
ws.onopen = function() {
    ws.send(JSON.stringify({ body: 'Hello' }));
};

The route syntax is the same as for HTTP routes (see Routing): dynamic parameters {name}, a wildcard *, the flags @text, @binary and @csrf, middleware with #, and +SOCKET / -SOCKET for authorized and unauthorized users. The maximum size of one message is CONF.$wsmaxsize (256 kB). Change it per route with a third argument in bytes, or with <1MB in the URL:

ROUTE('SOCKET /upload/ <5MB', upload);
ROUTE('SOCKET /feed/', feed, 1024 * 1024);

One WebSocket object per URL

The action does not run for each client. It runs once per URL, when the first client connects; later clients join the same WebSocket object. With a dynamic route, every distinct URL gets its own object, so /room/sport/ and /room/music/ are two separate groups of clients:

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

function room() {
    var self = this;
    // self.params.name === 'sport'
    self.on('message', function(client, message) {
        self.send({ room: self.params.name, body: message.body });
    });
}

self.url, self.params, self.online (the number of connected clients) and self.connections (an object { id: client }) describe the group.

Message formats

A route reads and writes JSON by default: an incoming message is parsed (messages that are not valid JSON are ignored), and send() serializes objects with JSON.stringify(). Two flags change it:

Flagmessage event receivessend() writes
(none)a parsed objectJSON
@texta stringJSON, or the string as it is with client.send(text, true)

ROUTE('SOCKET /terminal/ @text', function() {
    this.on('message', function(client, text) {
        client.send(text.toUpperCase(), true);
    });
});

The message event also gets the size of the message in bytes as its third argument.

Sending messages

client.send(message) writes to one client. websocket.send(message, [comparer]) writes to every client of the group; the optional comparer(client, message) returns true for the clients that should get it:

self.send({ type: 'notify' }, function(client) {
    return client.user && client.user.isadmin;
});

websocket.find(fn) returns the first client for which fn(client) returns true:

var target = self.find(function(client) {
    return client.user && client.user.id === message.to;
});
target && target.send({ type: 'private', body: message.body });

Notifying clients from outside the route

An action or an HTTP route often changes data that connected clients have to know about. The WebSocket object is created inside the SOCKET route, so keep a reference to it in the global MAIN object and use that reference from any other file.

Create controllers/live.js:

exports.install = function() {
    ROUTE('SOCKET /live/', live);
    ROUTE('POST /api/products/ --> products_create');
    ROUTE('POST /api/maintenance/', maintenance);
};

function live() {
    MAIN.live = this;
}

function maintenance($) {
    MAIN.live && MAIN.live.send({ type: 'maintenance', message: $.body.message });
    $.success();
}

Create actions/products.js (see Actions):

var products = [];

NEWACTION('products_create', {
    input: '*name:String',
    action: function($, model) {

        var product = { id: UID(), name: model.name };
        products.push(product);

        MAIN.live && MAIN.live.send({ type: 'product_created', product: product });

        $.callback(product);
    }
});

Connect from the browser:

var ws = new WebSocket('ws://localhost:8000/live/');

ws.onmessage = function(e) {
    var msg = JSON.parse(e.data);
    if (msg.type === 'product_created')
        console.log('New product:', msg.product.name);
};

A request to POST /api/products/ with the body {"name":"Keyboard"} now saves the product, sends the product_created message to every connected client and answers the request. The route POST /api/maintenance/ does the same from a plain route function. A request that fails the validation of the action sends no message.

The route action runs when the first client connects, so MAIN.live is undefined until then. The check MAIN.live && covers that moment: the action or the route answers normally and no message is sent. After the last client leaves, MAIN.live stays set and send() reaches nobody. Messages are not stored, so a client that connects later receives only the messages sent after it connected.

When the route uses autodestroy(), clear the reference in its callback. The next client that connects runs the route action again and sets a new reference:

function live() {
    var self = this;
    MAIN.live = self;
    self.autodestroy(function() {
        MAIN.live = null;
    });
}

A route with a dynamic URL has one WebSocket object per URL, so keep one reference per URL:

MAIN.rooms = {};

exports.install = function() {
    ROUTE('SOCKET /rooms/{name}/', room);
    ROUTE('POST /api/rooms/{name}/', notify);
};

function room() {
    MAIN.rooms[this.params.name] = this;
}

function notify($) {
    var room = MAIN.rooms[$.params.name];
    room && room.send({ type: 'notice', message: $.body.message });
    $.success();
}

The client

Each client is a WebSocket controller with the data of the HTTP upgrade request: client.id, client.ip, client.user, client.query, client.params, client.headers, client.url, client.ua, client.mobile, client.robot, client.language and client.latency. client.cookie(name) reads a cookie. Store your own data on the object if you need it later:

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

Authorization, CSRF and middleware

Before a client is accepted, the framework calls your authorization delegate (see Authorization). The user it returns is in client.user. A route declared with +SOCKET accepts only authorized users and -SOCKET only anonymous ones; a client that does not match any route gets the handshake and is then closed with the code 4001, so the browser sees a normal close event with that code and can, for example, ask the user to sign in:

ROUTE('+SOCKET /notifications/', notifications);

The @csrf flag requires a valid CSRF token in the x-csrf-token header or in the ?csrf= query argument (browsers cannot set headers on a WebSocket, so use the query). Middleware declared with #name runs before the connection is upgraded (see Middleware). Requests from IP addresses in CONF.$blacklist are refused.

Closing and cleaning up

client.close([code], [message]) closes one client, websocket.close([code], [message]) closes all of them. The default code is 1000. A message larger than the route size closes the client with 1009; invalid compressed data with 1003.

websocket.destroy() closes all clients, emits destroy and removes the object; the next client that connects runs the action again. websocket.autodestroy([callback]) does it for you 5 seconds after the last client leaves, which is the usual choice for dynamic rooms:

function room() {
    var self = this;
    var timer = setInterval(function() {
        self.send({ type: 'tick' });
    }, 1000);
    self.autodestroy(function() {
        clearInterval(timer);
    });
}

The global event websocket_end is emitted when any client disconnects: ON('websocket_end', function(websocket, client) {}).

Compression and encoding

When the browser offers permessage-deflate and CONF.$wscompress is true (default), messages are compressed in both directions, text and binary (@binary) messages alike. An error of the compression reaches the error event of the WebSocket object. Two more options transform every message:

  • CONF.$wsencodedecode = true sends messages through encodeURIComponent() and decodes incoming messages with decodeURIComponent().
  • websocket.encrypt() encrypts outgoing and decrypts incoming messages of the group with CONF.secret_encryption. Both sides must use the same key.

Ping and latency

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.

client.ping() pings one client yourself.

Removing a route

ROUTE() returns the route. route.remove() removes it and destroys all its WebSocket objects, so every client is disconnected:

var route = ROUTE('SOCKET /live/', live);

// later
route.remove();

WebSocket client

WEBSOCKETCLIENT([callback]) connects your application to another WebSocket server. Set the options and the events, then call connect():

var client = WEBSOCKETCLIENT();

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

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

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

client.on('close', function(code, reason) {
    console.log('closed', code, reason);
});

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

Options of client.options:

OptionDefaultDescription
type'json''json', 'text' or 'binary'
compresstrueOffer permessage-deflate to the server
reconnect3000Delay in ms before a reconnection after the connection closes; 0 disables it
reconnectservertrue also reconnects when the connection cannot be opened
maskingfalseMask outgoing frames (required by servers that follow the RFC strictly)
encodedecodefalseEncode/decode messages with encodeURIComponent()
encryptA key: messages are encrypted and decrypted with it
size0Max. size in bytes of a decompressed message (0 no limit)
rejectunauthorizedfalseReject invalid TLS certificates
timeout30000TCP keep-alive delay in ms for the socket (0 disables it)

key, cert and dhparam are passed to the TLS connection. client.close([code], [message]) closes the connection and stops reconnecting; client.close(code, true) closes it and keeps the reconnection. client.ping([timeout]) sends a ping; when the pong does not arrive in timeout ms (3000), the client emits error with a Timeout error, closes the connection and reconnects. client.latency holds the last measured time in ms.

Configuration

KeyDefaultDescription
$wsmaxsize256Max. size of a message in kB
$wscompresstrueAllow permessage-deflate compression
$wsencodedecodefalseEncode/decode all messages with URI encoding
$wsmaxlatency2000Max. latency in ms before a client is closed by the ping check
Made in Europe