sockolate
v1.1.1
Published
Sweet, Tasty WebSockets with enriched feature flavors
Downloads
47
Maintainers
Readme
sockolate
sockolate is a versatile and and feature-rich WebSocket handler to handle even the most advance WebSocket use-cases easily and quickly.
pnpm i sockolateFeatures
While WebSockets are already feature-rich for secure and fast bidirectional data connections, many use cases require even more fine-grained WebSockets to easily handle errors or connection problems.
Which is why sockolate enhances WebSockets with:
- Extra Events
- Aborting Connections
- Reconnections
- Inward and outward data buffering
- Connection Pausing
- Keep-Alive-Timers
- Pinging
- Heartbeat Connections
Usage
To use WebSockets, sockolate provides a Socket class that just works like a WebSocket:
import Socket from 'sockolate'
const socket = new Socket('ws://localhost:3000/api')
socket.connect()
// Or shorter:
new Socket('ws://localhost:3000/api', { immediate: true })Events
sockolate provides vast and complex lifecycle events for a lot of features and procedures you can do with the Socket. Those include:
preConnectbefore the internal WebSocket is created.openwhen the WebSocket has successfully connected with the server.dataon receiving messages. The handler holds the received message.sendon sending messages.closewhen the WebSocket is closing. HoldsCloseEventmetadata.erroron receiving an Error from either the server or theSocket. It holds an error object.aborton forced and abrupt closure of the connection. It holds the same error object.reconnecton initiating a reconnectionpingon sending a ping message.pongon receiving a ping response from the server.
Furthermore, Socket distinguishes between central callbacks and events. Central callbacks hold the actual logic and state management that surround the actual event listeners of the WebSocket. The events are only secondary and accompany the actual callbacks. They are intended for use in external handling.
import Socket from 'sockolate'
const socket = new Socket('ws://localhost:3000/api')
// Central callbacks
socket.onOpen(() => {})
socket.onClose(() => {})
socket.onError(() => {})
socket.onData(() => {})
// Events
socket.on('open', () => {})
socket.on('reconnect', () => {})
socket.on('ping', () => {})Aborting Connections
sockolate extends WebSockets by being able to forcefully and manually close the connection and end server processing by utilizing AbortControllers.
It directly sends a signal of {"type": "abort"} that can be loaded with extra payload to handle the connection closure on the server side.
import Socket from 'sockolate'
const socket = new Socket('ws://localhost:3000/api')
socket.connect()
// Sends { "type": "abort", "payload": { "id": 123 } } to the server.
socket.abort('Manual Closure', { id: 123 })Reconnections
When a connection receives an error, is aborted, closes or a reconnection was triggered manually, the Socket tries to disconnect and re-establish the connection:
import Socket from 'sockolate'
const socket = new Socket('ws://localhost:3000/api', { retry: { amount: 4, minUpTime: 500, startDelay: 1000, maxDelay: 30000, onAbort: true }})
socket.connect()
socket.on('reconnect', () => {
console.log("Reconnecting!")
})
// If onAbort is true, the socket can be aborted and will try to reconnect
socket.abort('Reconnect')
// You can also manually reconnect
socket.reconnect()Pausing and Buffers
Socket improves upon the built-in WebSocket message buffering by allowing bidirectional message buffering. You can pause the buffer and it will hold all processes and message parsing and sending. Buffering is on by default and will release all buffers immediately on resume:
import Socket from 'sockolate'
const socket = new Socket('ws://localhost:3000/api', { buffer: { max: 32, min: 0 }})
socket.connect()
// Sending data
socket.send('Test')
socket.send(5, (x: number) => x.toString()) // Sending data with custom parser!
// Pausing the socket
socket.pause()
// Data will be buffered
socket.send('Test2')
socket.send(5, (x: number) => x.toString())
console.log(socket.bufferedAmount)
// Releases all buffers.
socket.resume()You can also deactivate buffering entirely (except for the built-in buffering) by setting { buffer: false }.
Pinging and Heartbeat
To keep WebSockets alive, Socket has not only an internal keepalive timer that disconnects the connection based on the maximum timeout passed into the options, it also allows to ping the server and establish a heartbeat connection. A heartbeat connection will run indefinitely, but won't start if there is already a ping.:
import Socket from 'sockolate'
// Defines a heartbeat interval of 3s, a ping timeout of 5s and strictly errors on no response.
const socket = new Socket('ws://localhost:3000/api', { ping: { heartbeat: 3000, ping: 5000, strict: true }, timeout: 30000 })
socket.connect()
// Sends a signal of { "type": "ping" } to the server.
// It expects a signal of { "type": "pong" } . In strict mode, it aborts, if no answer comes from the server.
socket.ping()
// Initiates the heartbeat.
socket.startBeat()
console.log(socket.beating)
socket.stopBeat()© Torathion 2025
