---
title: WebSocket
project: Total.js V4
version: 0.0.99
section: reference
language: it
license: MIT
url: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/websockets/
updated: 2026-11-16T15:41:00.817Z
---

# WebSocket

> La route SOCKET, il controller WebSocket, il client connesso e WEBSOCKETCLIENT().

Una route `SOCKET` crea un controller WebSocket condiviso da tutti i client di un URL; ogni connessione è un oggetto client, e `WEBSOCKETCLIENT()` si connette dal server ad altri server WebSocket. La guida [WebSocket](../../guides/websockets/) spiega come usarli con esempi; questa pagina è il riferimento esatto.

## API

### ROUTE('SOCKET /url/', action, [flags], [length])

Type: `method`

Dichiara una route WebSocket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | `SOCKET /path/`, facoltativamente con `+`/`-`, `{params}` e `@apiname` |
| `action` | `Function` | yes |  | Inizializza il controller WebSocket |
| `flags` | `Array` | yes |  | Flag, origini, protocolli, middleware, una lunghezza o un oggetto di opzioni |
| `length` | `Number` | yes |  | Dimensione massima del messaggio in kB |

Returns: `FrameworkRoute` L'istanza della route

L'URL inizia con `SOCKET` (o `WS`, `WSS`). Un `+` o `-` davanti limita la route agli utenti autenticati o anonimi. `action` viene eseguita una sola volta, quando il primo client si connette all'URL, con il controller WebSocket come `this` e i parametri dinamici dell'URL come argomenti. `length` è la dimensione massima di un messaggio in kB (predefinito `CONF.default_websocket_maxlength`, `2`). Con `@name` nell'URL e senza azione, la route elabora la WebSocket API `@name` e si distrugge quando l'ultimo client se ne va.

I flag sono descritti nella voce **WebSocket route flags**.

Example: Route di chat
```js
exports.install = function() {
	ROUTE('SOCKET /chat/{room}/', chat, ['json'], 32);
};

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

Example: WebSocket API senza azione
```js
exports.install = function() {
	ROUTE('API @chat -messages_list *Messages --> list');
	ROUTE('SOCKET /chat/ @chat');
};
```

### ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])

Type: `config`

Flag che impostano il tipo di dati, l'accesso, le origini e i protocolli di una route WebSocket.

- `json` (predefinito): i messaggi in arrivo vengono analizzati come JSON (il JSON non valido viene ignorato) e gli oggetti in uscita vengono serializzati.
- `text`, `plain`: i messaggi sono stringhe; gli oggetti che invii vengono serializzati come JSON.
- `binary`: i messaggi sono oggetti `Buffer`.
- `raw`: disattiva `json` e `binary` (modalità testo).
- `buffer`: l'evento `message` riceve sempre il `Buffer` grezzo.
- `authorize`, `authorized`, `logged` / `unauthorize`, `unauthorized`, `unlogged`: solo utenti autenticati o anonimi.
- `@role`: un flag di ruolo; rende la route `authorize`.
- `http://...`, `https://...`: origini consentite; l'`Origin` della richiesta deve contenerne una.
- `#middleware`, `&middleware`: nomi di middleware.
- `id:name`: l'identificatore della route.
- `get`, `csrf`, `http`, `https`, `debug`, `release`: flag standard delle route.
- Qualsiasi altra parola è un sotto-protocollo obbligatorio. Ogni protocollo elencato deve essere nell'intestazione `Sec-WebSocket-Protocol` del client, altrimenti la connessione viene chiusa con `4001`.
- Un numero è la dimensione massima del messaggio in kB; un oggetto sono le opzioni del middleware.

Example: Route binaria per un'origine
```js
ROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);

function upload() {
	this.on('message', function(client, buffer) {
		// buffer is a Buffer
	});
}
```

Example: Sotto-protocollo obbligatorio
```js
// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');
ROUTE('SOCKET /rpc/', rpc, ['rpc']);
```

### websocket.online

Type: `property`

Il numero di client connessi.

Returns: `Number`

Aggiornato ogni volta che un client si connette o si disconnette.

Example: Trasmettere il conteggio
```js
function counter() {
	var self = this;
	self.on('open', function() {
		self.send({ online: self.online });
	});
}
```

### websocket.connections

Type: `property`

Tutti i client connessi, per id.

Returns: `Object`

Un oggetto le cui chiavi sono gli id dei client e i cui valori sono gli oggetti client. `websocket.keys` contiene gli stessi id come array. `websocket.id` è la chiave del controller in `F.connections`: l'URL seguito da `#` e dai flag della route.

Example: Leggere un client
```js
var client = this.connections['15'];
```

### websocket.url

Type: `property`

L'URL della connessione.

Returns: `String`

Il percorso a cui si è connesso il primo client, con una barra finale.

### websocket.params

Type: `property`

I parametri dinamici dell'URL.

Returns: `Object`

Ogni `{name}` della route diventa una chiave. Gli stessi valori arrivano come argomenti dell'azione.

Example: Nome della stanza
```js
ROUTE('SOCKET /rooms/{name}/', room);

function room(name) {
	// name === this.params.name
}
```

### websocket.repository

Type: `property`

Un oggetto per i tuoi dati.

Returns: `Object`

Creato al primo accesso e mantenuto per tutta la vita del controller.

Example: Conservare la cronologia
```js
function chat() {
	var self = this;
	self.repository.history = [];
	self.on('message', function(client, message) {
		self.repository.history.push(message);
	});
}
```

### websocket.on(name, callback)

Type: `method`

Registra un gestore di eventi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dell'evento |
| `callback` | `Function` | yes |  | Gestore |

Returns: `WebSocket` Il controller

Eventi: `open`, `close`, `message`, `error` e `destroy`. `this` nel gestore è il controller. `once(name, fn)` registra un gestore per una sola chiamata, `removeListener(name, fn)` e `removeAllListeners([name])` rimuovono i gestori, e `emit(name, [args...])` chiama i gestori dei tuoi eventi.

Example: Eventi
```js
function chat() {
	this.on('open', function(client) {});
	this.on('message', function(client, message) {});
	this.on('close', function(client, code, message) {});
}
```

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

Type: `method`

Invia un messaggio a tutti i client o ai client che selezioni.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object/String/Buffer` | yes |  | Il messaggio |
| `comparer` | `Function` | yes |  | `function(client, message, params)` restituisce `true` per inviare |
| `replacer` | `Function/Boolean` | yes |  | Replacer JSON |
| `params` | `Object` | yes |  | Valore passato a `comparer` |

Returns: `WebSocket`

In una route `json` il messaggio viene serializzato una sola volta e inviato a ogni client. `comparer(client, message, params)` restituisce `true` per i client che ricevono il messaggio. `replacer` viene passato a `JSON.stringify()`; `true` usa il replacer JSON del framework. Quando il terzo argomento non è una funzione, viene usato come `params`.

Example: Tutti tranne il mittente
```js
self.on('message', function(client, message) {
	self.send(message, function(c) {
		return c !== client;
	});
});
```

Example: Con params
```js
self.send({ type: 'refresh' }, function(client, message, params) {
	return client.user && client.user.role === params.role;
}, { role: 'admin' });
```

### websocket.find(fn)

Type: `method`

Trova il primo client che corrisponde a una funzione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(client)` restituisce `true` per il client cercato |

Returns: `Object` Il client o `undefined`

Restituisce `undefined` quando nessun client corrisponde.

Example: Trovare un utente
```js
var client = this.find(function(client) {
	return client.user && client.user.id === userid;
});
client && client.send({ type: 'notify' });
```

### websocket.clients()

Type: `method`

Restituisce tutti i client connessi come array.

Returns: `Array`

Example: Elencare gli utenti
```js
var users = this.clients().map(function(client) {
	return client.user ? client.user.name : 'anonymous';
});
```

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

Type: `method`

Chiude tutti i client connessi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | yes |  | Motivo della chiusura |
| `code` | `Number` | yes |  | Codice di chiusura, predefinito `1000` |

Returns: `WebSocket`

Ogni client riceve un frame di chiusura con `code` (predefinito `1000`) e `message`. Il controller resta; usa `destroy()` per rimuoverlo.

Example: Chiudere tutti
```js
this.close('Server restart', 4000);
```

### websocket.destroy()

Type: `method`

Chiude tutti i client e rimuove il controller.

Returns: `WebSocket`

Emette `destroy`, rimuove il controller da `F.connections` e lo libera. Il client successivo dell'URL crea un nuovo controller.

### websocket.autodestroy([callback])

Type: `method`

Distrugge il controller quando nessun client è online.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | Chiamata prima che il controller venga distrutto |

Returns: `WebSocket`

Quando l'ultimo client si disconnette e nessuno si connette entro 5 secondi, viene chiamato `callback` (con il controller come `this`) e il controller viene distrutto. Chiamarlo di nuovo aggiunge un'altra callback.

Example: Distruzione automatica
```js
function room() {
	this.autodestroy(function() {
		console.log('Destroyed', this.url);
	});
}
```

### websocket.ping()

Type: `method`

Invia un ping a tutti i client.

Returns: `WebSocket`

Il framework lo chiama da solo ogni `CONF.default_interval_websocket_ping` ms. La risposta pong imposta `client.latency`.

### websocket.api(name)

Type: `method` · Since: `0.0.44`

Elabora i messaggi della WebSocket API.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dell'API, con o senza `@` |

Returns: `WebSocket`

Registra un gestore `message` che esegue le route `API` con il `@name` indicato per i messaggi il cui `TYPE` è `api`. Il `data` del messaggio è `{ schema: 'operation/param', data: {} }`; la risposta viene rimandata al client quando il messaggio ha `callbackid`, con `success: true` e `data`, oppure `error: true` e gli elementi di errore.

Example: Elaborare un'API
```js
exports.install = function() {
	ROUTE('API @chat -messages_list *Messages --> list');
	ROUTE('SOCKET /chat/', chat);
};

function chat() {
	this.api('@chat');
	this.autodestroy();
}
```

### websocket.encrypt([enable])

Type: `method`

Cifra i messaggi con `CONF.secret_encryption`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | yes |  | Predefinito `true` |

Returns: `WebSocket`

Quando è abilitato e `CONF.secret_encryption` è impostato, i messaggi di testo in uscita vengono cifrati e quelli in arrivo decifrati. Senza argomento abilita la cifratura.

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

Type: `event`

Un client si è connesso.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `client` | `Object` | yes |  | Il nuovo client |

Emesso dopo che il client si è unito al controller, quindi `this.online` lo conta già.

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

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

Type: `event`

Un client ha inviato un messaggio.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `client` | `Object` | yes |  | Il mittente |
| `message` | `Object/String/Buffer` | yes |  | Il messaggio |

`message` è un oggetto nelle route `json`, una stringa nelle route `text` e un `Buffer` nelle route `binary` o `buffer`.

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

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

Type: `event`

Un client si è disconnesso.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `client` | `Object` | yes |  | Il client |
| `code` | `Number` | yes |  | Codice di chiusura |
| `message` | `String` | yes |  | Motivo della chiusura |

`code` e `message` provengono dal frame di chiusura del client, quando ne ha inviato uno.

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

Type: `event`

Si è verificato un errore del socket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error` | yes |  | L'errore |
| `client` | `Object` | yes |  | Il client |

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

Type: `event`

Il controller sta per essere distrutto.

### client.id

Type: `property`

L'id univoco della connessione.

Returns: `String`

Una stringa numerica. È disponibile anche come `client.ID` ed è la chiave in `websocket.connections`. `client.online` è `true` finché la connessione è aperta, e `client.controller` (o `client.container`) è il controller WebSocket.

### client.user

Type: `property`

L'utente accettato da `AUTH()`.

Returns: `Object`

Puoi anche assegnare un valore. `client.session` e `client.sessionid` contengono i valori di sessione della richiesta.

Example: Messaggio privato
```js
var client = self.find(function(c) {
	return c.user && c.user.id === message.to;
});
```

### client.query

Type: `property`

La query string dell'URL della connessione.

Returns: `Object`

I valori sono stringhe. `client.get` è un alias.

Example: Token nell'URL
```js
// new WebSocket('wss://example.com/live/?channel=sport')
this.on('open', function(client) {
	client.channel = client.query.channel;
});
```

### client.headers

Type: `property`

Le intestazioni della richiesta di upgrade.

Returns: `Object`

Disponibili anche: `client.ip`, `client.ua`, `client.url`, `client.uri`, `client.mobile`, `client.language` e `client.req`. `client.protocol` è l'array dei sotto-protocolli da `Sec-WebSocket-Protocol`.

### client.latency

Type: `property`

La latenza dell'ultimo ping in ms.

Returns: `Number`

Impostata quando il client risponde a un ping. I client senza risposta o con una latenza superiore a `CONF.default_websocket_maxlatency` vengono chiusi.

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

Type: `method`

Invia un messaggio a questo client.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object/String/Buffer` | yes |  | Il messaggio |
| `raw` | `Boolean` | yes |  | Non serializzare (route json) |
| `replacer` | `Function/Boolean` | yes |  | Replacer JSON; `true` usa il replacer del framework |

Returns: `Object` Il client

In una route `json` gli oggetti vengono serializzati; con `raw` impostato a `true` il messaggio viene inviato così com'è (una stringa JSON che hai già). In una route `text` gli oggetti vengono serializzati e gli altri valori convertiti in stringhe. In una route `binary` il messaggio deve essere un `Buffer`. Non succede nulla se il client è chiuso.

Example: Rispondere
```js
this.on('message', function(client, message) {
	client.send({ ok: true, id: message.id });
});
```

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

Type: `method`

Chiude questa connessione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | yes |  | Motivo della chiusura |
| `code` | `Number` | yes |  | Codice di chiusura, predefinito `1000` |

Returns: `Object` Il client

Invia un frame di chiusura con `code` (predefinito `1000`) e `message`. Gli argomenti possono essere passati anche nell'ordine `(code, message)`.

Example: Espellere un client
```js
client.close('Kicked', 4100);
```

### client.cookie(name)

Type: `method`

Legge un cookie della richiesta di upgrade.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del cookie |

Returns: `String`

Example: Leggere un cookie
```js
var token = client.cookie('token');
```

### client.hostname([path])

Type: `method`

Restituisce l'hostname con un percorso facoltativo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | Percorso da aggiungere |

Returns: `String`

`client.host()` è un alias.

### F.findConnection(path)

Type: `method`

Trova un controller WebSocket tramite il suo id.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String/RegExp` | yes |  | Parte dell'id o un'espressione regolare |

Returns: `WebSocket` Il controller o `undefined`

Restituisce il primo controller il cui id contiene `path` (o corrisponde a una `RegExp`). I controller sono tenuti in `F.connections`.

Example: Inviare da una route HTTP
```js
function notify() {
	var ws = F.findConnection('/notifications/');
	ws && ws.send({ type: 'refresh' });
	this.success();
}
```

### F.findConnections([path])

Type: `method`

Trova controller WebSocket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String/RegExp` | yes |  | Parte dell'id o un'espressione regolare |

Returns: `Array`

Senza `path` restituisce tutti i controller.

Example: Tutte le stanze
```js
F.findConnections('/rooms/').forEach(function(ws) {
	ws.send({ type: 'shutdown' });
});
```

### ON('websocket_begin', function(controller, client) {})

Type: `event`

Un client si è unito a un controller WebSocket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `WebSocket` | yes |  | Il controller |
| `client` | `Object` | yes |  | Il client |

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

Type: `event`

Un client ha lasciato un controller WebSocket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `WebSocket` | yes |  | Il controller |
| `client` | `Object` | yes |  | Il client |

### CONF.default_websocket_maxlength

Type: `config`

La dimensione massima predefinita del messaggio in kB.

Returns: `Number`

Predefinito `2`. Una route lo sovrascrive con il suo `length`.

### CONF.default_websocket_maxlatency

Type: `config` · Since: `0.0.59`

La latenza massima del ping in ms.

Returns: `Number`

Predefinito `2000`. I client con una latenza superiore, o senza pong, vengono chiusi. `0` disattiva il ping. Il ping viene eseguito ogni `CONF.default_interval_websocket_ping` ms (predefinito `20000`; i valori inferiori a `1000` usano `20000`).

### CONF.allow_websocket

Type: `config`

Abilita le route WebSocket.

Returns: `Boolean`

Predefinito `true`. `CONF.allow_websocket_compression` (predefinito `true`) consente `permessage-deflate`, e `CONF.default_websocket_encodedecode` (predefinito `false`) attiva la codifica URI dei messaggi.

### WEBSOCKETCLIENT([callback])

Type: `method`

Crea un client WebSocket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(client)` |

Returns: `WebSocketClient`

`callback(client)` viene chiamata subito con il nuovo client (anche come `this`). Imposta lì opzioni, intestazioni ed eventi, poi chiama `client.connect()`.

Example: Connettersi
```js
WEBSOCKETCLIENT(function(client) {
	client.on('open', function() {
		client.send({ type: 'hello' });
	});
	client.on('message', function(message) {
		console.log(message);
	});
	client.connect('wss://example.com/chat/');
});
```

### websocketclient.options

Type: `property`

Opzioni del client.

Returns: `Object`

- `type` (`'json'`): `json`, `text`, `binary` o `buffer`.
- `compress` (`true`): richiede `permessage-deflate`.
- `reconnect` (`3000`): ms prima di riconnettersi dopo la chiusura della connessione; `0` lo disattiva.
- `reconnectserver` (`false`): si riconnette anche dopo un errore di connessione o una risposta HTTP inattesa.
- `masking` (`false`): applica il masking ai frame in uscita.
- `encodedecode` (`false`): codifica URI dei messaggi.
- `encrypt`: un segreto per cifrare e decifrare i messaggi di testo.
- `length`: dimensione massima di un messaggio decompresso in byte.
- `rejectunauthorized` (`false`): rifiuta i certificati TLS non validi.
- `key`, `cert`, `dhparam`: opzioni TLS.

Example: Client di testo
```js
WEBSOCKETCLIENT(function(client) {
	client.options.type = 'text';
	client.options.reconnect = 10000;
	client.connect('ws://127.0.0.1:8000/log/');
});
```

### websocketclient.headers

Type: `property`

Intestazioni aggiuntive della richiesta di upgrade.

Returns: `Object`

`websocketclient.cookies` è un oggetto di cookie inviati nell'intestazione `Cookie`.

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

### websocketclient.closed

Type: `property`

`true` quando il client non è connesso.

Returns: `Boolean`

`websocketclient.reconnect` conta le riconnessioni.

### websocketclient.latency

Type: `property` · Since: `0.0.44`

La latenza dell'ultimo ping in ms.

Returns: `Number`

Impostata quando il server risponde a `ping()`.

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

Type: `method`

Apre la connessione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String/Object` | yes |  | URL del server |
| `protocol` | `String` | yes |  | Sotto-protocollo |
| `origin` | `String` | yes |  | Origine |

`url` inizia con `ws://` o `wss://`. Può essere anche un oggetto `{ socket: '/path/to/unix.socket', path: '/chat/' }`. `protocol` viene inviato in `Sec-WebSocket-Protocol` e `origin` in `Sec-WebSocket-Origin`. La connessione parte al tick successivo.

Example: Con un protocollo
```js
client.connect('wss://example.com/rpc/', 'rpc');
```

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

Type: `method`

Invia un messaggio.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object/String/Buffer` | yes |  | Il messaggio |
| `raw` | `Boolean` | yes |  | Non serializzare (json) |
| `replacer` | `Function/Boolean` | yes |  | Replacer JSON |

Returns: `Boolean` `true` quando è stato inviato

Con `type: 'json'` gli oggetti vengono serializzati (a meno che `raw` sia `true`). Con `text` gli oggetti vengono serializzati e gli altri valori convertiti in stringhe. Con `binary` o `buffer` un messaggio che non è un `Buffer` viene convertito in `Buffer`. Restituisce `false` quando il client è chiuso.

Example: Inviare
```js
if (!client.send({ type: 'ping' }))
	console.log('Not connected');
```

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

Type: `method`

Chiude la connessione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String/Boolean` | yes |  | Motivo della chiusura, o `true` per riconnettersi |
| `code` | `Number` | yes |  | Codice di chiusura, predefinito `1000` |

Returns: `WebSocketClient`

Invia un frame di chiusura con `code` (predefinito `1000`). Interrompe anche la riconnessione, a meno che `message` sia `true`: in quel caso la connessione si chiude e il client si riconnette. Gli argomenti possono essere passati come `(code, message)`.

Example: Riconnettersi
```js
// Close and connect again after options.reconnect ms
client.close(true);
```

### websocketclient.destroy()

Type: `method` · Since: `0.0.42`

Libera il client e interrompe la riconnessione.

Emette `destroy` e rimuove tutti i gestori di eventi.

### websocketclient.ping([timeout])

Type: `method` · Since: `0.0.44`

Invia un ping al server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `timeout` | `Number` | yes |  | Predefinito `3000` ms |

Returns: `WebSocketClient`

Se non arriva un pong entro `timeout` ms (predefinito `3000`), il client emette `error` con `'Timeout'` e si chiude. Il pong imposta `latency`.

Example: Misurare la latenza
```js
setInterval(function() {
	client.ping(5000);
}, 30000);
```

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

Type: `method` · Since: `0.0.44`

Chiama la WebSocket API di un server Total.js.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Operazione, ad es. `'messages_read/123'` |
| `data` | `Object` | yes |  | Payload |
| `callback` | `Function` | yes |  | `function(err, response)` |
| `timeout` | `Number` | yes |  | Predefinito `5000` ms |

Returns: `WebSocketClient`

Invia `{ TYPE: 'api', data: { schema, data } }`. `callback(err, response)` riceve la risposta; `err` è `408` dopo `timeout` ms (predefinito `5000`). Senza `schema` registra solo il gestore delle risposte.

Example: Chiamare un'operazione
```js
client.api('messages_list', { page: 1 }, function(err, response) {
	if (err)
		console.log(err);
	else
		console.log(response);
});
```

### websocketclient.on(name, callback)

Type: `method`

Registra un gestore di eventi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dell'evento |
| `callback` | `Function` | yes |  | Gestore |

Returns: `WebSocketClient`

Eventi: `open()`, `message(data)`, `close(code, message)`, `error(err)` e `destroy()`. `once()`, `removeListener()`, `removeAllListeners()` ed `emit()` funzionano come nel controller.

Example: Eventi
```js
client.on('open', function() {});
client.on('message', function(data) {});
client.on('close', function(code, message) {});
client.on('error', function(err) {});
```

### client.session

Type: `property`

La sessione della connessione.

Returns: `Object`

La sessione impostata dal tuo delegato `AUTH()` per la richiesta di upgrade. `client.sessionid` è il suo id. Può essere impostata.

Example: Esempio
```js
function socket() {
	this.on('open', function(client) {
		console.log(client.sessionid, client.session);
	});
}
```

### client.ping()

Type: `method`

Invia un frame di ping a questo client.

Returns: `Object` Il client.

La risposta del client aggiorna `client.latency`. `websocket.ping()` invia un ping a tutti i client.

Example: Ping a un client
```js
function socket() {
	this.on('open', function(client) {
		client.ping();
	});
}
```

### websocketclient.url

Type: `property`

L'URL dell'ultimo `connect()`.

Returns: `String`

`websocketclient.protocol` e `websocketclient.origin` conservano gli altri argomenti di `connect()`.

Example: Esempio

```js
WEBSOCKETCLIENT(function(client) {
	client.connect('wss://example.com/live/');
	client.on('open', function() {
		console.log('Connected to', client.url);
	});
});
```
