Convert Figma logo to code with AI

joewalnes logoreconnecting-websocket

A small decorator for the JavaScript WebSocket API that automatically reconnects

4,227
968
4,227
78

Top Related Projects

21,639

Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

Real-time messaging library for Go. The simplest way to add feature-rich and scalable WebSocket support to your application. The core of Centrifugo server.

Pusher Javascript library

Realtime application framework (client)

Quick Overview

Reconnecting WebSocket is a small JavaScript library that wraps the WebSocket API to provide automatic reconnection functionality. It aims to create a robust WebSocket connection that automatically reconnects when the connection is lost, making it ideal for applications requiring persistent real-time communication.

Pros

  • Automatic reconnection handling, saving developers time and effort
  • Configurable reconnection strategy with customizable delay and maximum retries
  • Seamless API that mimics the native WebSocket, making it easy to integrate into existing projects
  • Lightweight and dependency-free, suitable for various JavaScript environments

Cons

  • Limited to WebSocket protocol, not suitable for other real-time communication methods
  • May not be actively maintained, with the last significant update several years ago
  • Lacks advanced features like connection pooling or load balancing
  • No built-in support for secure WebSocket connections (wss://)

Code Examples

Creating a basic reconnecting WebSocket:

const socket = new ReconnectingWebSocket('ws://example.com/socket');

socket.onopen = function(event) {
    console.log('Connection established');
};

socket.onmessage = function(event) {
    console.log('Message received:', event.data);
};

Customizing reconnection options:

const socket = new ReconnectingWebSocket('ws://example.com/socket', null, {
    reconnectInterval: 3000,
    maxReconnectAttempts: 10
});

Manually closing and reopening the connection:

socket.close();

// Later, when you want to reconnect
socket.open();

Getting Started

  1. Include the library in your HTML file:
<script src="https://cdn.jsdelivr.net/npm/reconnecting-websocket@4.4.0/dist/reconnecting-websocket.min.js"></script>
  1. Create a new ReconnectingWebSocket instance:
const socket = new ReconnectingWebSocket('ws://your-websocket-server.com');

socket.onopen = function() {
    console.log('Connected');
    socket.send('Hello, Server!');
};

socket.onmessage = function(event) {
    console.log('Received:', event.data);
};

socket.onclose = function() {
    console.log('Disconnected');
};

This setup creates a WebSocket connection that will automatically attempt to reconnect if the connection is lost.

Competitor Comparisons

21,639

Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

Pros of ws

  • More comprehensive WebSocket implementation with advanced features
  • Actively maintained with frequent updates and bug fixes
  • Supports both client and server-side WebSocket connections

Cons of ws

  • Requires more setup and configuration for basic usage
  • Doesn't include built-in reconnection functionality
  • Larger package size due to its extensive feature set

Code Comparison

reconnecting-websocket:

const socket = new ReconnectingWebSocket('ws://example.com');
socket.onopen = () => console.log('Connected');
socket.onmessage = (event) => console.log('Received:', event.data);

ws:

const WebSocket = require('ws');
const socket = new WebSocket('ws://example.com');
socket.on('open', () => console.log('Connected'));
socket.on('message', (data) => console.log('Received:', data));

Summary

reconnecting-websocket is a lightweight library focused on providing automatic reconnection functionality for WebSocket connections. It's easy to use and requires minimal setup, making it ideal for simple applications that need reliable WebSocket connections.

ws is a more robust and feature-rich WebSocket library that offers greater flexibility and control over WebSocket connections. It's suitable for complex applications that require advanced WebSocket functionality, but it may be overkill for simpler use cases and requires additional setup for features like automatic reconnection.

Real-time messaging library for Go. The simplest way to add feature-rich and scalable WebSocket support to your application. The core of Centrifugo server.

Pros of Centrifuge

  • Full-featured real-time messaging server with client libraries
  • Supports multiple protocols (WebSocket, SockJS, HTTP-streaming)
  • Scalable architecture for high-performance applications

Cons of Centrifuge

  • More complex setup and configuration
  • Steeper learning curve due to additional features
  • Requires server-side implementation

Code Comparison

Reconnecting-websocket:

var socket = new ReconnectingWebSocket("ws://...");
socket.onmessage = function(event) {
    console.log(event.data);
};

Centrifuge:

var centrifuge = new Centrifuge("ws://...");
centrifuge.subscribe("channel", function(message) {
    console.log(message.data);
});
centrifuge.connect();

Summary

Reconnecting-websocket is a lightweight library focused on providing automatic WebSocket reconnection, while Centrifuge is a more comprehensive real-time messaging solution. Reconnecting-websocket is easier to implement for simple use cases, but Centrifuge offers more advanced features and scalability for complex applications. The choice between the two depends on the specific requirements of your project and the level of functionality needed.

Pusher Javascript library

Pros of pusher-js

  • Full-featured real-time messaging library with advanced functionality
  • Supports multiple protocols (WebSockets, HTTP streaming, long-polling)
  • Extensive documentation and community support

Cons of pusher-js

  • Requires a Pusher account and API key
  • More complex setup and configuration
  • Larger library size and potential overhead

Code Comparison

reconnecting-websocket:

var socket = new ReconnectingWebSocket('ws://....');
socket.onmessage = function(event) {
    console.log(event.data);
};

pusher-js:

var pusher = new Pusher('APP_KEY');
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
    console.log(data);
});

Summary

reconnecting-websocket is a lightweight, single-purpose library focused on maintaining a WebSocket connection with automatic reconnection. It's simple to use and has no external dependencies.

pusher-js is a comprehensive real-time messaging solution with more features and flexibility. It offers multiple protocols and advanced functionality but requires a Pusher account and more setup.

Choose reconnecting-websocket for basic WebSocket needs with automatic reconnection. Opt for pusher-js when you need a full-featured real-time messaging system with scalability and additional protocols.

Realtime application framework (client)

Pros of Socket.IO Client

  • Full-featured library with support for various transports (WebSocket, polling, etc.)
  • Built-in support for real-time events, broadcasting, and namespaces
  • Extensive documentation and large community support

Cons of Socket.IO Client

  • Larger file size and more complex implementation
  • Requires a Socket.IO server, not compatible with standard WebSocket servers
  • May introduce additional latency due to its protocol overhead

Code Comparison

Socket.IO Client:

const socket = io('https://example.com');
socket.on('connect', () => {
  console.log('Connected');
  socket.emit('custom_event', { data: 'Hello' });
});

Reconnecting WebSocket:

const socket = new ReconnectingWebSocket('wss://example.com');
socket.onopen = () => {
  console.log('Connected');
  socket.send(JSON.stringify({ type: 'custom_event', data: 'Hello' }));
};

Summary

Socket.IO Client offers a more comprehensive solution with additional features and transport options, making it suitable for complex real-time applications. However, it comes at the cost of increased complexity and file size. Reconnecting WebSocket provides a simpler, lightweight solution focused solely on maintaining a WebSocket connection, which may be preferable for projects with basic WebSocket needs and compatibility with standard WebSocket servers.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

ReconnectingWebSocket

A small JavaScript library that decorates the WebSocket API to provide a WebSocket connection that will automatically reconnect if the connection is dropped.

It is API compatible, so when you have:

var ws = new WebSocket('ws://....');

you can replace with:

var ws = new ReconnectingWebSocket('ws://....');

Minified library with gzip compression is less than 600 bytes.

How reconnections occur

With the standard WebSocket API, the events you receive from the WebSocket instance are typically:

onopen
onmessage
onmessage
onmessage
onclose // At this point the WebSocket instance is dead.

With a ReconnectingWebSocket, after an onclose event is called it will automatically attempt to reconnect. In addition, a connection is attempted repeatedly (with a small pause) until it succeeds. So the events you receive may look something more like:

onopen
onmessage
onmessage
onmessage
onclose
// ReconnectingWebSocket attempts to reconnect
onopen
onmessage
onmessage
onmessage
onclose
// ReconnectingWebSocket attempts to reconnect
onopen
onmessage
onmessage
onmessage
onclose

This is all handled automatically for you by the library.

Parameters

var socket = new ReconnectingWebSocket(url, protocols, options);

url

protocols

options

  • Options (see below)

Options

Options can either be passed as the 3rd parameter upon instantiation or set directly on the object after instantiation:

var socket = new ReconnectingWebSocket(url, null, {debug: true, reconnectInterval: 3000});

or

var socket = new ReconnectingWebSocket(url);
socket.debug = true;
socket.timeoutInterval = 5400;

debug

  • Whether this instance should log debug messages or not. Debug messages are printed to console.debug().
  • Accepts true or false
  • Default value: false

automaticOpen

  • Whether or not the websocket should attempt to connect immediately upon instantiation. The socket can be manually opened or closed at any time using ws.open() and ws.close().
  • Accepts true or false
  • Default value: true

reconnectInterval

  • The number of milliseconds to delay before attempting to reconnect.
  • Accepts integer
  • Default: 1000

maxReconnectInterval

  • The maximum number of milliseconds to delay a reconnection attempt.
  • Accepts integer
  • Default: 30000

####reconnectDecay

  • The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist.
  • Accepts integer or float
  • Default: 1.5

timeoutInterval

  • The maximum time in milliseconds to wait for a connection to succeed before closing and retrying.
  • Accepts integer
  • Default: 2000

maxReconnectAttempts

  • The maximum number of reconnection attempts that will be made before giving up. If null, reconnection attempts will be continue to be made forever.
  • Accepts integer or null.
  • Default: null

binaryType

  • The binary type is required by some applications.
  • Accepts strings 'blob' or 'arraybuffer'.
  • Default: 'blob'

Methods

ws.open()

  • Open the Reconnecting Websocket

ws.close(code, reason)

ws.refresh()

  • Refresh the connection if still open (close and then re-open it).

ws.send(data)

  • Transmits data to the server over the WebSocket connection.
  • Accepts @param data a text string, ArrayBuffer or Blob

Like this? Check out websocketd for the simplest way to create WebSocket backends from any programming language.

Follow @joewalnes

Bitdeli Badge

NPM DownloadsLast 30 Days