---
title: OpenClient
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/openclient/
updated: 2026-11-18T16:57:39.578Z
---

# OpenClient

> OPENCLIENT(): un client WebSocket per i messaggi verso altri servizi.

## API

### OPENCLIENT(url, [id])

Type: `method`

Apre un client WebSocket condiviso per messaggi di richiesta e risposta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'indirizzo del server (`ws://`, `wss://`, `http://` o `https://`). |
| `id` | `String` | no | `GUID(10)` | L'identificatore del client. |

Returns: `Object` Il client.

Si connette a `url` tramite WebSocket (`http` diventa `ws`, `https` diventa `wss`) e si riconnette automaticamente. I client con lo stesso URL condividono una sola connessione; la connessione si chiude quando viene rimosso il suo ultimo client. Passare un `id` esistente rimuove prima il vecchio client con quell'id.

Il client ha questi metodi:

- `send(msg, [callback], [timeout])` invia un messaggio JSON. Con una callback, il messaggio riceve un `callbackid`, e la callback `function(err, response)` viene eseguita quando il server risponde con lo stesso `callbackid` (campi `error` e `response`). Mentre la connessione è assente riprova ogni 500 ms, fino a dieci volte, poi richiama la callback con `offline`. Un timeout produce `timeout`.
- `rpc(msg, [timeout])` come `send()`, ma restituisce una promise.
- `cmd(msg, [timeout])` invia senza attendere una risposta.
- `message(fn)`, `error(fn)` e `online(fn)` impostano gli handler. `online(meta)` viene eseguito con il messaggio `init` del server, e con `null` quando la connessione si chiude.
- `close()` o `remove()` rimuove il client.

Proprietà: `id`, `url`, `connected`, `meta` (l'ultimo messaggio `init`).

Example: Interrogare il server
```js
var client = OPENCLIENT('https://service.example.com/');

client.message(function(msg) {
	console.log('Message:', msg);
});

client.send({ type: 'ping' }, function(err, response) {
	console.log(err, response);
}, 5000);

var stats = await client.rpc({ type: 'stats' }, 5000);
```
