WebSockets
The WebSocket object, its clients, WEBSOCKETCLIENT() and the WebSocket configuration.
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.
ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])| Parameter | Type | Description |
|---|---|---|
url |
String |
Method, path, flags and middleware |
action |
Function |
Called with the WebSocket object |
size? |
Number |
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.
exports.install = function() {
ROUTE('SOCKET /room/{name}/', room);
};
function room() {
var self = this;
self.on('message', function(client, message) {
self.send(message);
});
}
ROUTE('+SOCKET /console/ @text <1MB', terminal);
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.
CONF.$wsmaxsizeReturns Number
Default 256. A larger message closes the client with code 1009. A route can set its own size.
$wsmaxsize : 512
config
CONF.$wscompress
Allows permessage-deflate compression.
CONF.$wscompressReturns Boolean
Default true. When the browser offers permessage-deflate, messages are compressed in both directions.
$wscompress : false
config
CONF.$wsencodedecode
Encodes and decodes all WebSocket messages with URI encoding.
CONF.$wsencodedecodeReturns 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.
$wsencodedecode : true
config
CONF.$wsmaxlatency
- latency in ms before the ping check closes a client.
CONF.$wsmaxlatencyReturns 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.
$wsmaxlatency : 5000
class
function() { var websocket = this; }
The object that groups all clients of one WebSocket URL.
function() { var websocket = this; }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).
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.
websocket.onlineReturns Number
self.on('open', function() {
self.send({ type: 'online', count: self.online });
});
property
websocket.connections
The connected clients as an object { id: client }.
websocket.connectionsReturns Object
for (var id in self.connections) {
var client = self.connections[id];
}
property
websocket.params
The dynamic parameters of the URL.
websocket.paramsReturns Object
Filled from the first client of the URL; all clients of the object share the same values.
ROUTE('SOCKET /room/{name}/', function() {
var name = this.params.name;
});
property
websocket.url
The URL of the group in lower case.
websocket.urlReturns String
method
websocket.send(message, [comparer], [replacer], [params])
Sends a message to all clients, or to the clients chosen by a comparer.
websocket.send(message, [comparer], [replacer], [params])| Parameter | Type | Description |
|---|---|---|
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.
self.send({ type: 'refresh' });
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.
websocket.find(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(client) returning a boolean |
Returns Controller The client, or undefined
var client = self.find(function(client) {
return client.user && client.user.id === id;
});
method
websocket.close([code], [message])
Closes all clients.
websocket.close([code], [message])| Parameter | Type | Description |
|---|---|---|
code? |
Number |
The close code Default: 1000 |
message? |
String |
The close reason |
Returns WebSocket
The WebSocket object stays, so new clients can connect.
self.close(4000, 'Maintenance');
method
websocket.destroy()
Closes all clients and removes the WebSocket object.
websocket.destroy()Emits destroy. The next client that connects to the URL runs the route action again and gets a new object.
self.destroy();
method
websocket.autodestroy([callback])
Destroys the object 5 seconds after the last client leaves.
websocket.autodestroy([callback])| Parameter | Type | Description |
|---|---|---|
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.
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.
websocket.encrypt([enable])| Parameter | Type | Description |
|---|---|---|
enable? |
Boolean |
Default: true |
With no argument or true it enables encryption; false disables it. It does nothing while CONF.secret_encryption is empty.
function secure() {
this.encrypt();
}
method
websocket.ping()
Pings all clients.
websocket.ping()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.
self.ping();
method
websocket.error(err)
Logs an error with the URL of the WebSocket.
websocket.error(err)| Parameter | Type | Description |
|---|---|---|
err |
Error|String |
A string is converted to an Error. The error goes to the framework error log.
self.on('message', function(client, message) {
if (!message.type)
self.error('Missing type');
});
event
websocket.on('open', function(client) {})
A client has connected.
websocket.on('open', function(client) {})| Parameter | Type | Description |
|---|---|---|
client |
Controller |
The new client |
self.on('open', function(client) {
client.send({ type: 'welcome' });
});
event
websocket.on('message', function(client, message, size) {})
A client has sent a message.
websocket.on('message', function(client, message, size) {})| Parameter | Type | Description |
|---|---|---|
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.
self.on('message', function(client, message) {
client.send(message);
});
event
websocket.on('close', function(client, code, message) {})
A client has disconnected.
websocket.on('close', function(client, code, message) {})| Parameter | Type | Description |
|---|---|---|
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.
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.
websocket.on('error', function(err, client) {})| Parameter | Type | Description |
|---|---|---|
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.
self.on('error', function(err, client) {
self.error(err);
});
event
websocket.on('destroy', function() {})
The WebSocket object is being destroyed.
websocket.on('destroy', function() {})Emitted by destroy() and autodestroy().
self.on('destroy', function() {
clearInterval(timer);
});
event
ON('websocket_end', function(websocket, client) {})
Any client of any WebSocket route has disconnected.
ON('websocket_end', function(websocket, client) {})| Parameter | Type | Description |
|---|---|---|
websocket |
WebSocket |
|
client |
Controller |
ON('websocket_end', function(websocket, client) {
console.log(websocket.url, client.ip);
});
class
client
One connected client of a WebSocket route.
clientClients 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.
self.on('open', function(client) {
client.nick = client.query.nick || 'guest';
});
property
client.id
A unique identifier of the client.
client.idReturns String
Also client.ID. It is the key in websocket.connections.
client.send({ id: client.id });
property
client.user
The user returned by the authorization delegate.
client.userReturns Object
undefined for anonymous clients.
self.on('open', function(client) {
client.send({ name: client.user ? client.user.name : 'guest' });
});
property
client.ip
The IP address of the client.
client.ipReturns String
The first address of X-Forwarded-For behind a proxy.
property
client.query
The query string of the WebSocket URL as an object.
client.queryReturns Object
Use it to pass data that browsers cannot send in headers, such as a token.
// new WebSocket('ws://localhost:8000/live/?token=abc')
var token = client.query.token;
property
client.params
The dynamic parameters of the URL.
client.paramsReturns Object
property
client.headers
The headers of the upgrade request, with lower-case names.
client.headersReturns Object
property
client.latency
The time in ms between the last ping and its pong.
client.latencyReturns Number
Each ping resets it to null; the pong sets the measured time.
self.on('message', function(client) {
client.send({ latency: client.latency });
});
property
client.address
The full URL the client connected to.
client.addressReturns 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.
client.uaReturns 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.
client.send(message, [raw], [replacer])| Parameter | Type | Description |
|---|---|---|
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().
client.send({ type: 'pong' });
client.send('OK', true);
method
client.close([code], [message])
Closes the connection with the client.
client.close([code], [message])| Parameter | Type | Description |
|---|---|---|
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.
self.on('open', function(client) {
if (!client.query.token)
client.close(4003, 'Forbidden');
});
method
client.ping()
Sends a ping to the client.
client.ping()Returns Controller The same client
The pong sets client.latency.
method
client.cookie(name)
Reads a cookie of the upgrade request.
client.cookie(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Returns String The decoded value, or an empty string
var sid = client.cookie('sid');
method
client.hostname([path])
Returns the protocol and host of the request, with an optional path.
client.hostname([path])| Parameter | Type | Description |
|---|---|---|
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.
client.destroy()
method
WEBSOCKETCLIENT([callback])
Creates a WebSocket client that connects to another server.
WEBSOCKETCLIENT([callback])| Parameter | Type | Description |
|---|---|---|
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().
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.
wsclient.connect(url, [protocol], [origin])| Parameter | Type | Description |
|---|---|---|
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.
client.connect('wss://example.com/live/');
property
wsclient.options
The options of the client.
wsclient.optionsReturns 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.
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.
wsclient.headersReturns Object
Set them before connect().
client.headers['x-token'] = 'secret';
method
wsclient.send(message, [raw], [replacer])
Sends a message to the server.
wsclient.send(message, [raw], [replacer])| Parameter | Type | Description |
|---|---|---|
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.
client.send({ type: 'subscribe', channel: 'news' });
method
wsclient.sendcustom(type, message)
Sends one message as text or binary, regardless of options.type.
wsclient.sendcustom(type, message)| Parameter | Type | Description |
|---|---|---|
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.
client.sendcustom('binary', Buffer.from([1, 2, 3]));
method
wsclient.close([code], [message])
Closes the connection.
wsclient.close([code], [message])| Parameter | Type | Description |
|---|---|---|
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.
client.close();
method
wsclient.destroy()
Destroys the connection and stops reconnecting.
wsclient.destroy()Emits destroy.
client.destroy();
method
wsclient.ping([timeout])
Sends a ping and waits for the pong.
wsclient.ping([timeout])| Parameter | Type | Description |
|---|---|---|
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.
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.
wsclient.api(schema, [data], [callback], [timeout])| Parameter | Type | Description |
|---|---|---|
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.
var response = await client.api('users_list', { page: 1 });
event
wsclient.on('message', function(message, size) {})
A message from the server.
wsclient.on('message', function(message, size) {})| Parameter | Type | Description |
|---|---|---|
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.
wsclient.on('open', function() {})Also emitted after each reconnection.
event
wsclient.on('close', function(code, message) {})
The connection was closed.
wsclient.on('close', function(code, message) {})| Parameter | Type | Description |
|---|---|---|
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.
wsclient.on('error', function(err) {})| Parameter | Type | Description |
|---|---|---|
err |
Error |
client.on('error', function(err) {
console.log('WS error', err.message);
});
method
route.remove()
since 0.0.17
Removes a route registered with ROUTE().
route.remove()For a SOCKET route it removes the route and destroys all its WebSocket objects, so every connected client is disconnected.
var route = ROUTE('SOCKET /live/', live);
route.remove();