Common usage
Initialising Sarus
Sarus provides a number of options when initialising an instance:
const sarus = new Sarus({
url: 'wss://ws.anephenix.com',
binaryType: 'arraybuffer',
eventListeners: {
open: [() => {}],
message: [event => {}],
error: [error => {}],
close: [() => {}],
},
reconnectAutomatically: true,
retryConnectionDelay: true,
storageType: 'local',
protocols: 'hybi-00',
retryProcessTimePeriod: 50,
storageKey: 'sarus'
});
Below is a table of all of those options:
Parameter | Type | Description |
---|---|---|
url | string | The url for the WebSocket server |
binaryType | string | An optional parameter to set the type of binary data passed via the WebSocket connection, blob or arraybuffer |
eventListeners | object | An object consisting of keys with functions to call when an event is emitted by the WebSocket. |
reconnectAutomatically | boolean | If set to false, then Sarus will not try to reconnect when the WebSocket connection is closed. |
retryConnectionDelay | boolean number | Determines if there should be a delay to retrying to connect, so that you don't end up with the thundering herd problem. Can be passed as true to apply a 1000ms delay, or a number in milliseconds. |
storageType | string | An optional parameter to use the web browser's sessionStorage or localStorage cache to persist messages. |
protocols | string array | An optional parameter used to specify the sub-protocol that the WebSocket connection should use. |
retryProcessTimePeriod | number | An optional parameter used to help buffer the time between trying to resend a message over a WebSocket connection. By default it is a number, 50 (for 50 milliseconds). |
storageKey | string | A key that is used with sessionStorage and localStorage to store and retrieve the messages in the message queue. By default it is set to 'sarus'. |
Attaching event listener functions
If you want to attach event listener functions to the sarus instance, you can do that by using the "on" function call:
// Logs messages to the console for debugging
const logMessage = (event) => {
console.log(event.data);
};
// Attach the event listener
sarus.on('message', logMessage);
Below is a table of the parameters to pass to the function:
Parameter | Type | Description |
---|---|---|
event | string | The WebSocket event to trigger the function for. Can be one of open, message, error or close. |
function | function | The function to trigger when the WebSocket event is emitted. |
You can add as many event listener functions as you wish.
Removing event listener functions
In case that you want to remove an event listener function, you can do that by calling the 'off' function:
/*
Remove a function from the Sarus
event listener by function variable
*/
sarus.off('message', logMessage);
/*
You can also remove the event Listener
by the name of the function
*/
sarus.off('message', 'parseMessage');
Below is a table of the parameters to pass to the function:
Parameter | Type | Description |
---|---|---|
event | string | The WebSocket event to remove the function for. Can be one of open, message, error or close. |
function | string variable | The function to remove. Can be either the name of the function as a string, or the variable that the function is assigned to. |
extra options | object | An optional 3rd parameter argument. Can be used to tell the function to not throw an error if no function is found to remove, e.g. { doNotThrowError: true } |
Sending messages
Sending messages in Sarus is identical to how you would send messages with a WebSocket:
sarus.send('Hello world');
Below is a table of the parameters to pass to the function:
Parameter | Type | Description |
---|---|---|
message | string array object number boolean function | The message to send over the WebSocket. Can be any value that can be encoded into JSON. |
Closing the connection
If you want to close the WebSocket connection (for example when the user logs off from an app), then you can do that by calling this:
sarus.disconnect();
Calling that function on the sarus client will do 2 things:
- Set the reconnectAutomatically flag to false.
- Close the WebSocket connection.
Event listeners listening on the WebSocket's close event will still trigger, but the client will not attempt to reconnect automatically.
Below is a table of the parameters to pass to the function:
Parameter | Type | Description |
---|---|---|
reconnectAutomatically | boolean | An optional parameter to pass, telling the function to not set the reconnectAutomatically flag to false. |
Advanced usage
Here you will get to see some of the advanced features of Sarus in action
Persisting messages with browser storage
Sarus uses a message queue to handle the messages that need to be sent over the WebSocket. When the WebSocket's status is open, the messages are sent. If there isn't an open connection, then the messages are kept in the queue.
In such a case, visitors might try to refresh their web browser, and if that happens, then those messages in the queue would be lost. If there's a case where you want to guarantee messages for delivery (such as pending chat messages to be sent), then you can use Sarus' message storage feature to persist the message queue.
The message queue is persisted with HTML5 browser storage, and there are two options - session storage, and local storage. Below is an example of how to configure Sarus to use session storage for the browser.
const sarus = new Sarus({
url: 'wss://ws.anephenix.com',
storageType: 'session',
});
This example above configures Sarus to use HTML5 session storage to persist the message queue. This means that the messages on the queue will persist between web page refreshes. You can inspect your browser's web storage to see the message queue persisted in the browser.
If you need the messages on the queue to be persisted beyond web browser restarts, then you can use HTML5 local storage to persist the message queue, like in the example below:
const sarus = new Sarus({
url: 'wss://ws.anephenix.com',
storageType: 'local',
});
The message queue is stored as a JSON array of messages, stringified in order to store in web browser storage.
Note - If you are persisting the message queue alongside messages sent in relation to a user using an app, consider wiping the browser storage when the user logs out of the app.
By default, the key used in HTML5 web storage for storing the messages is 'sarus', but you can customise that by passing the storageKey option as demonstrated in the example below:
const sarus = new Sarus({
url: 'wss://ws.anephenix.com',
storageType: 'local',
storageKey: 'persistedMessages',
});
Delaying reconnection attempts
When a WebSocket connection closes Sarus will attempt to automatically reconnect without any delay. If you want to add a delay before Sarus tries to reconnect the WebSocket, you can do that by passing the 'retryConnectionDelay' option in the configuration for Sarus:
const sarus = new Sarus({
url: 'wss://ws.anephenix.com',
retryConnectionDelay: true,
});
The option of passing a boolean will add a delay of 1000ms (1 second) before trying to reconnect. Alternatively, if you want to specify the amount of time to delay the reconnection by, you can pass a number instead (in milliseconds):
const sarus = new Sarus({
url: 'wss://ws.anephenix.com',
retryConnectionDelay: 500, // 500ms or 1/2 second
});
Delaying message sending re-attempts
As part of the message queue, Sarus applies a 50ms delay before attempting to resend a message (in the case that the attempt to send a message failed). If you wish to, you can set the time period in milliseconds like this:
const sarus = new Sarus({
url: 'wss://ws.anephenix.com',
retryProcessTimePeriod: 25, // 25ms
});