---
title: WebSockets
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/websockets/
updated: 2026-11-19T16:17:12.159Z
---

# WebSockets

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

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](../../guides/websockets/).

## API

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

Type: `method`

Registers a WebSocket route.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | Method, path, flags and middleware |
| `action` | `Function` | yes |  | Called with the WebSocket object |
| `size` | `Number` | no | `CONF.$wsmaxsize * 1024` | Max. size of one message in bytes |

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.

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

function room() {
	var self = this;
	self.on('message', function(client, message) {
		self.send(message);
	});
}
```

Example: Authorized users, text messages, 1 MB
```js
ROUTE('+SOCKET /console/ @text <1MB', terminal);
```

Example: Binary messages
```js
ROUTE('SOCKET /files/ @binary', function($) {
	$.on('message', function(client, buffer) {
		client.send(buffer); // a binary frame back
	});
});
```

### CONF.$wsmaxsize

Type: `config`

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.

Example: config file
```js
$wsmaxsize		: 512
```

### CONF.$wscompress

Type: `config`

Allows `permessage-deflate` compression.

Returns: `Boolean`

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

Example: Disable compression
```js
$wscompress	   : false
```

### CONF.$wsencodedecode

Type: `config`

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.

Example: config file
```js
$wsencodedecode   : true
```

### CONF.$wsmaxlatency

Type: `config`

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

Example: config file
```js
$wsmaxlatency	 : 5000
```

### function() { var websocket = this; }

Type: `class`

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`).

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

### websocket.online

Type: `property`

The number of connected clients.

Returns: `Number`

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

### websocket.connections

Type: `property`

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

Returns: `Object`

Example: Iterate
```js
for (var id in self.connections) {
	var client = self.connections[id];
}
```

### websocket.params

Type: `property`

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.

Example: Room name
```js
ROUTE('SOCKET /room/{name}/', function() {
	var name = this.params.name;
});
```

### websocket.url

Type: `property`

The URL of the group in lower case.

Returns: `String`

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

Type: `method`

Sends a message to all clients, or to the clients chosen by a comparer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object|String|Buffer` | yes |  | The message |
| `comparer` | `Function` | no |  | `function(client, message, params)` returning a boolean |
| `replacer` | `Function` | no |  | A JSON replacer |
| `params` | `Object` | no |  | 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`.

Example: Everyone
```js
self.send({ type: 'refresh' });
```

Example: Only admins
```js
self.send({ type: 'alert' }, function(client) {
	return client.user && client.user.isadmin;
});
```

### websocket.find(fn)

Type: `method`

Finds the first client for which `fn(client)` returns `true`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(client)` returning a boolean |

Returns: `Controller` The client, or `undefined`

Example: By user
```js
var client = self.find(function(client) {
	return client.user && client.user.id === id;
});
```

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

Type: `method`

Closes all clients.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | no | `1000` | The close code |
| `message` | `String` | no |  | The close reason |

Returns: `WebSocket`

The WebSocket object stays, so new clients can connect.

Example: Close everyone
```js
self.close(4000, 'Maintenance');
```

### websocket.destroy()

Type: `method`

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.

Example: Destroy
```js
self.destroy();
```

### websocket.autodestroy([callback])

Type: `method`

Destroys the object 5 seconds after the last client leaves.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | 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.

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

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

### websocket.encrypt([enable])

Type: `method`

Encrypts and decrypts all messages of the group with `CONF.secret_encryption`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` |  |

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

Example: Enable
```js
function secure() {
	this.encrypt();
}
```

### websocket.ping()

Type: `method`

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.

Example: Ping now
```js
self.ping();
```

### websocket.error(err)

Type: `method`

Logs an error with the URL of the WebSocket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error|String` | yes |  |  |

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

Example: Log
```js
self.on('message', function(client, message) {
	if (!message.type)
		self.error('Missing type');
});
```

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

Type: `event`

A client has connected.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `client` | `Controller` | yes |  | The new client |

Example: Welcome
```js
self.on('open', function(client) {
	client.send({ type: 'welcome' });
});
```

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

Type: `event`

A client has sent a message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `client` | `Controller` | yes |  |  |
| `message` | `Object|String|Buffer` | yes |  |  |
| `size` | `Number` | yes |  |  |

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

Example: Echo
```js
self.on('message', function(client, message) {
	client.send(message);
});
```

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

Type: `event`

A client has disconnected.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `client` | `Controller` | yes |  |  |
| `code` | `Number` | yes |  |  |
| `message` | `String` | yes |  |  |

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

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

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

Type: `event`

An error on a client socket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error` | yes |  |  |
| `client` | `Controller` | yes |  |  |

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.

Example: Log
```js
self.on('error', function(err, client) {
	self.error(err);
});
```

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

Type: `event`

The WebSocket object is being destroyed.

Emitted by `destroy()` and `autodestroy()`.

Example: Cleanup
```js
self.on('destroy', function() {
	clearInterval(timer);
});
```

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

Type: `event`

Any client of any WebSocket route has disconnected.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `websocket` | `WebSocket` | yes |  |  |
| `client` | `Controller` | yes |  |  |

Example: Global log
```js
ON('websocket_end', function(websocket, client) {
	console.log(websocket.url, client.ip);
});
```

### client

Type: `class`

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.

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

### client.id

Type: `property`

A unique identifier of the client.

Returns: `String`

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

Example: Send id
```js
client.send({ id: client.id });
```

### client.user

Type: `property`

The user returned by the authorization delegate.

Returns: `Object`

`undefined` for anonymous clients.

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

### client.ip

Type: `property`

The IP address of the client.

Returns: `String`

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

### client.query

Type: `property`

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.

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

### client.params

Type: `property`

The dynamic parameters of the URL.

Returns: `Object`

### client.headers

Type: `property`

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

Returns: `Object`

### client.latency

Type: `property`

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.

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

### client.address

Type: `property`

The full URL the client connected to.

Returns: `String`

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

### client.ua

Type: `property`

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.

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

Type: `method`

Sends a message to one client.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object|String|Buffer` | yes |  |  |
| `raw` | `Boolean` | no | `false` | Send a string without JSON serialization (`@text` routes) |
| `replacer` | `Function` | no |  | 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()`.

Example: JSON
```js
client.send({ type: 'pong' });
```

Example: Plain text
```js
client.send('OK', true);
```

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

Type: `method`

Closes the connection with the client.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | no | `1000` | The close code |
| `message` | `String` | no |  | The close reason |

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

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

### client.ping()

Type: `method`

Sends a ping to the client.

Returns: `Controller` The same client

The pong sets `client.latency`.

### client.cookie(name)

Type: `method`

Reads a cookie of the upgrade request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  |  |

Returns: `String` The decoded value, or an empty string

Example: Session
```js
var sid = client.cookie('sid');
```

### client.hostname([path])

Type: `method`

Returns the protocol and host of the request, with an optional path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no |  | Appended to the host |

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

### client.destroy()

Type: `method`

Destroys the socket immediately, without a close frame.

### WEBSOCKETCLIENT([callback])

Type: `method`

Creates a WebSocket client that connects to another server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | `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()`.

Example: Connect
```js
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/');
});
```

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

Type: `method`

Opens the connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String|Object` | yes |  |  |
| `protocol` | `String` | no |  |  |
| `origin` | `String` | no |  |  |

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

Example: Secure
```js
client.connect('wss://example.com/live/');
```

### wsclient.options

Type: `property`

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.

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

### wsclient.headers

Type: `property`

Extra headers of the upgrade request.

Returns: `Object`

Set them before `connect()`.

Example: Token
```js
client.headers['x-token'] = 'secret';
```

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

Type: `method`

Sends a message to the server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object|String|Buffer` | yes |  |  |
| `raw` | `Boolean` | no | `false` | Send a prepared JSON string |
| `replacer` | `Function` | no |  | 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.

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

### wsclient.sendcustom(type, message)

Type: `method`

Sends one message as text or binary, regardless of `options.type`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | `binary` or `text` |
| `message` | `String|Buffer` | yes |  |  |

Returns: `Boolean` `true` when the message was written

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

Example: Binary
```js
client.sendcustom('binary', Buffer.from([1, 2, 3]));
```

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

Type: `method`

Closes the connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | no | `1000` |  |
| `message` | `String|Boolean` | no |  | The close reason, or `true` |

Returns: `WebSocketClient`

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

Example: Close
```js
client.close();
```

### wsclient.destroy()

Type: `method`

Destroys the connection and stops reconnecting.

Emits `destroy`.

Example: Destroy
```js
client.destroy();
```

### wsclient.ping([timeout])

Type: `method`

Sends a ping and waits for the pong.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `timeout` | `Number` | no | `3000` | Time in ms |

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.

Example: Keep checking
```js
setInterval(function() {
	client.ping(5000);
}, 30000);
```

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

Type: `method`

Sends an API request over the connection and waits for the answer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  |  |
| `data` | `Object` | no |  |  |
| `callback` | `Function` | no |  | `function(err, response)` |
| `timeout` | `Number` | no | `5000` | Time in ms |

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.

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

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

Type: `event`

A message from the server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object|String|Buffer` | yes |  |  |
| `size` | `Number` | yes |  |  |

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

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

Type: `event`

The connection is open.

Also emitted after each reconnection.

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

Type: `event`

The connection was closed.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | yes |  |  |
| `message` | `String` | yes |  |  |

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

Type: `event`

A connection error, an unexpected HTTP response, an invalid server key or a ping timeout.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error` | yes |  |  |

Example: Log
```js
client.on('error', function(err) {
	console.log('WS error', err.message);
});
```

### route.remove()

Type: `method` · 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.

Example: Remove
```js
var route = ROUTE('SOCKET /live/', live);
route.remove();
```
