OpenClient
OPENCLIENT(): a WebSocket client for messages to other services.
On this page
API
method
OPENCLIENT(url, [id])
Opens a shared WebSocket client for request and response messages.
OPENCLIENT(url, [id])| Parameter | Type | Description |
|---|---|---|
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 acallbackid, and the callbackfunction(err, response)runs when the server answers with the samecallbackid(fieldserrorandresponse). While the connection is down it retries every 500 ms, up to ten times, then calls back withoffline. A timeout givestimeout.rpc(msg, [timeout])the same assend(), but returns a promise.cmd(msg, [timeout])sends without waiting for an answer.message(fn),error(fn)andonline(fn)set handlers.online(meta)runs with theinitmessage of the server, and withnullwhen the connection closes.close()orremove()removes the client.
Properties: id, url, connected, meta (the last init message).
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);