Sockette is a tiny (367 bytes) wrapper around WebSocket
that will automatically reconnect if the connection is lost!
In addition to attaching additional API methods, Sockette allows you to reuse instances, avoiding the need to redeclare all event listeners.
You have direct access to the (current) underlying WebSocket
within every EventListener
callback (via event.target
).
$ npm install --save sockett
Unlike WebSocket
, you should declare all event listeners on initialization:
import Sockett from 'sockett';
const ws = new Sockett('ws://localhost:3000', {
timeout: 5e3,
maxAttempts: 10,
});
ws.on('open', e => console.log('Connected!', e));
ws.on("message", e => console.log('Received:', e));
ws.on("reconnect", e => console.log('Reconnecting...', e));
ws.on("maximum" , e => console.log('Stop Attempting!', e));
ws.on('close', e => console.log('Closed!', e));
ws.on('error', e => console.log('Error:', e));
ws.send('Hello, world!');
ws.json({type: 'ping'});
ws.close(); // graceful shutdown
// Reconnect 10s later
setTimeout(ws.reconnect, 10e3);
Returns: Sockette
Returns the Sockette
instance.
Type: String
The URL you want to connect to — Should be prefixed with ws://
or wss://
. This is passed directly to WebSocket
.
Type: String|Array
Either a single protocol string or an array of strings used to indicate sub-protocols. See the WebSocket
docs for more info.
Type: Number
Default: 1000
The amount of time (in ms
) to wait in between reconnection attempts. Defaults to 1 second.
Type: Number
Default: Infinity
The maximum number of attempts to reconnect.
This is called when the connection has been closed for any reason.
Important: If the
event.code
is not1000
,1001
, or1005
an automatic reconnect attempt will be queued.
Important: If the
event.code
isECONNREFUSED
, an automatic reconnect attempt will be queued.
Identical to WebSocket.send()
, capable of sending multiple data types.
Identical to WebSocket.close()
.
Note: The
code
will default to1000
unless specified.
Convenience method that passes your obj
(Object) through JSON.stringify
before passing it to WebSocket.send()
.
If options.maxAttempts
has not been exceeded, enqueues a reconnection attempt. Otherwise, it runs your options.onmaximum
callback.
Initializes a new WebSocket
— used on initialization and by reconnect()
.
MIT © Luke Edwards