Spanish Total.js
English
Documentation For AI agents
Contents

OpenClient

OPENCLIENT(): a WebSocket client for messages to other services.

.md GitHub
On this page

API

method

OPENCLIENT(url, [id])

Opens a shared WebSocket client for request and response messages.
ParameterTypeDescription
url String The address of the server (ws://, wss://, http:// or https://).
id? String The client identifier. Default: GUID(10)

Returns Object The client.

Connects to url over WebSocket (http becomes ws, https becomes wss) and reconnects automatically. Clients with the same URL share one connection; the connection closes when its last client is removed. Passing an existing id removes the old client with that id first.

The client has these methods:

  • send(msg, [callback], [timeout]) sends a JSON message. With a callback, the message gets a callbackid, and the callback function(err, response) runs when the server answers with the same callbackid (fields error and response). While the connection is down it retries every 500 ms, up to ten times, then calls back with offline. A timeout gives timeout.
  • rpc(msg, [timeout]) the same as send(), but returns a promise.
  • cmd(msg, [timeout]) sends without waiting for an answer.
  • message(fn), error(fn) and online(fn) set handlers. online(meta) runs with the init message of the server, and with null when the connection closes.
  • close() or remove() removes the client.

Properties: id, url, connected, meta (the last init message).

Ask the server
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);
Made in Europe