Skip to content

tutekxd123/WebSocketSingleTonWrapper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 

Repository files navigation

WebSocketSingleTonWrapper

Lightweight WebSocket wrapper in vanilla JS with automatic reconnection, message queueing, and simple event registration.

What it does

WebSocketSingleton keeps one shared WebSocket connection, queues messages while the socket is not open, and tries to reconnect automatically when the connection is lost unexpectedly.

Usage

Add the WebSocketSingleton class to your frontend project, then create and initialize it once:

const ws = new WebSocketSingleton(
  "wss://example.com/ws", // url
  5,                      // reconnect tries
  5000,                   // open timeout in ms
  true,                   // reload page when initial connection closes with error
  {
    open: () => console.log("Connected"),
    message: (event) => console.log("Message:", event.data),
    close: () => console.log("Disconnected"),
    error: (event) => console.error("Socket error:", event),
  },
  1000                    // queued messages limit
);

await ws.init();

Send data normally:

ws.send(JSON.stringify({ type: "ping" }));

If the socket is not open yet, send() puts the data into an internal queue. The queue is flushed automatically when the connection opens again.

Register extra listeners later if needed:

ws.addEventListener("message", (event) => {
  console.log("Another handler:", event.data);
});

Close the connection manually:

ws.close();

Constructor

new WebSocketSingleton(url, triesReconnect, timeout, initReloadOnError, eventHandlers, limitQueue)
Parameter Description Default
url WebSocket server URL. required
triesReconnect How many reconnect attempts should be made after an unexpected close. 5
timeout How long to wait for the initial open event before rejecting. 5000
initReloadOnError If true, the page reloads 20 seconds after the initial connection closes unexpectedly. true
eventHandlers Optional object with open, message, close, and error callbacks. {}
limitQueue Maximum number of messages stored while the socket is unavailable. 1000

Main methods

Method Description
async init() Init the WebSocket connection. Resolving promise with event open
send(data) Sends data immediately or queues it until the socket is open.
addEventListener(event, callback) Adds a callback for open, message, close, or error.
GetInstance() Returns the raw shared WebSocket instance or null if it does not exist yet.
close() Closes the socket, clears the queue, and removes registered handlers.

Notes

  • Use this in browser environments where WebSocket and location.reload() are available.
  • After the socket has connected once, unexpected closes trigger automatic reconnection. The wrapper will try reconnect to WS, until reconnect attempts exceed limit. Use close() or EventListener to close WS
  • Implementation queue message doesn't guarantee message delivery or consistency in case of unexpected event or failures.
  • Queue messages may be lost, messages are stored in memory only.
  • Avoid creating multiple wrapper objects; keep one shared WebSocketSingleton reference in your app.

About

Lightweight Websocket wrapper in vanilla JS with automatic reconnection, message queueing.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors