The cutest little WebSocket wrapper! 🧦

Related tags

WebSocket sockette
Overview
Sockette

Sockette

The cutest little WebSocket wrapper! 🧦

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).

Install

$ npm install --save sockette

Usage

Unlike WebSocket, you should declare all event listeners on initialization:

const Sockette = require('sockette');

const ws = new Sockette('ws://localhost:3000', {
  timeout: 5e3,
  maxAttempts: 10,
  onopen: e => console.log('Connected!', e),
  onmessage: e => console.log('Received:', e),
  onreconnect: e => console.log('Reconnecting...', e),
  onmaximum: e => console.log('Stop Attempting!', e),
  onclose: e => console.log('Closed!', e),
  onerror: e => console.log('Error:', e)
});

ws.send('Hello, world!');
ws.json({type: 'ping'});
ws.close(); // graceful shutdown

// Reconnect 10s later
setTimeout(ws.reconnect, 10e3);

API

Sockette(url, options)

Returns: Sockette

Returns the Sockette instance.

url

Type: String

The URL you want to connect to — Should be prefixed with ws:// or wss://. This is passed directly to WebSocket.

options.protocols

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.

options.timeout

Type: Number
Default: 1000

The amount of time (in ms) to wait in between reconnection attempts. Defaults to 1 second.

options.maxAttempts

Type: Number
Default: Infinity

The maximum number of attempts to reconnect.

Important: Pass -1 if you want to disable this feature. Although, this is main reason to use Sockette! 😂

options.onopen

Type: Function

The EventListener to run in response to 'open' events. It receives the Event object as its only parameter.

This is called when the connection has been established and is ready to send and receive data.

Important: Sockette will forget the number of previous reconnection attempts, so that the next time connection is lost, you will consistently retry n number of times, as determined by options.maxAttempts.

options.onmessage

Type: Function

The EventListener to run in response to 'message' events. It receives the Event object as its only parameter.

This is called when a message has been received from the server. You'll probably want event.data!

options.onreconnect

Type: Function

The callback to run when attempting to reconnect to the server.

If Sockette is automatically reconnecting in response to an error or unexpected close event, then your onreconnect callback will receive the forwarded Event object.

options.onmaximum

Type: Function

The callback to run when the maxAttempts limit has been met.

This callback will receive the forwarded Event object from onclose.

options.onclose

Type: Function

The EventListener to run in response to 'close' events. It receives the Event object as its only parameter.

This is called when the connection has been closed for any reason.

Important: If the event.code is not 1000, 1001, or 1005 an automatic reconnect attempt will be queued.

options.onerror

Type: Function

The EventListener to run in response to 'error' events. It receives the Event object as its only parameter.

This is called anytime an error occurs.

Important: If the event.code is ECONNREFUSED, an automatic reconnect attempt will be queued.

send(data)

Identical to WebSocket.send(), capable of sending multiple data types.

close(code, reason)

Identical to WebSocket.close().

Note: The code will default to 1000 unless specified.

json(obj)

Convenience method that passes your obj (Object) through JSON.stringify before passing it to WebSocket.send().

reconnect()

If options.maxAttempts has not been exceeded, enqueues a reconnection attempt. Otherwise, it runs your options.onmaximum callback.

open()

Initializes a new WebSocket — used on initialization and by reconnect().

License

MIT © Luke Edwards

Comments
  • Force websocket close without reconnection how?

    Force websocket close without reconnection how?

    Hi pal,

    How do you intentional close the websocket without reconnection execution, its necessary to pass event code to close method?

    when manually invoke close method I think that the reconnection should not be done

    ws.close()
    

    thanks

    opened by outaTiME 20
  • Disable reconnect programmatically

    Disable reconnect programmatically

    Hi, awesome lib. Is there any way that we can disable reconnect programmatically ?

    For example, we init a sockette instance with maxAttempts by default(always enable recconnecting), after a several times of connection failure, I would like to provide a way to disable the further reconnecting manually. Thanks.

    question 
    opened by Symous 15
  • Can't truly shutdown connection when using close method

    Can't truly shutdown connection when using close method

    In my project, I want to shutdown the connection when I leave out. However, no matter the code I passed to close method, it failed, e.g. ," ws.close(1000, 'out')". Why?

    more info 
    opened by j78742 12
  • 1005 status code is incorrectly treated as

    1005 status code is incorrectly treated as "abnormal" shutdown

    If the close frame contains no status code (payload length == 0), the close code is 1005. In this case sockette should not reconnect.

    Ref: https://tools.ietf.org/html/rfc6455#section-7.1.5

    opened by lpinca 10
  • error occurs in IE11 and edge when connection is closed

    error occurs in IE11 and edge when connection is closed

    Environment: React 16.2, webpack 4.10, sockette 2.0.0

    in the react lifecycle method componentWillUnmount method, I will close the socket instance , the error occurs ,

    the code blow _20180927181119

    error blow _20180927181225 _20180927181247

    when I add annotation to the ws close method , it get ok, _20180927181606

    How can I fix this problem , thx.

    more info 
    opened by houyaowei 8
  • Websocket is undefined

    Websocket is undefined

    Hi, i have a problem when testing my component using mocha & chai, it says:

    ReferenceError: WebSocket is not defined
        at module.exports.r.open (/Users/bcw-001/dev/sofia_fe_react/node_modules/sockette/src/index.js:25:32)
        at new module.exports (/Users/bcw-001/dev/sofia_fe_react/node_modules/sockette/src/index.js:48:7)
    

    i use mock-websocket. anyone know what did i miss?

    opened by Ahershel 8
  • TypeError:

    TypeError: "Sockette is not a constructor" (Angular/TypeScript)

    I've created a new Angular project using the Angular CLI and have installed and attempted to import Sockette into my project (an empty Angular project.)

    I am getting the below error when trying to import/require Sockette.

    TypeError: "Sockette is not a constructor"
    
    1. Via import gets me the above error:
    import {Component} from '@angular/core';
    import {environment} from '../environments/environment';
    
    import * as Sockette from 'sockette';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      constructor() {
        const socket = new Sockette(environment.websocket_server);
      }
    }
    
    1. Via require gets me the same error above:
    import {Component} from '@angular/core';
    import {environment} from '../environments/environment';
    
    const Sockette = require('sockette');
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      constructor() {
        const socket = new Sockette(environment.websocket_server);
      }
    }
    

    When I console.log the Sockette object, I get the following:

    import {Component} from '@angular/core';
    import {environment} from '../environments/environment';
    
    const Sockette = require('sockette');
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      constructor() {
        console.log(Sockette);
        const socket = new Sockette(environment.websocket_server);
      }
    }
    
    Object { default: default(), … }
    

    Which lead me to try the following (which works!)

    import {Component} from '@angular/core';
    import {environment} from '../environments/environment';
    
    const Sockette = require('sockette');
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      constructor() {
        const socket = new Sockette.default(environment.websocket_server);
      }
    }
    

    I'm left assuming this is due to the way Sockette is being exported... any thoughts?

    opened by METACEO 7
  • Automatically split & re-combine messages over a certain size

    Automatically split & re-combine messages over a certain size

    Thank you for making this package! It's great.

    This is a feature request.

    AWS API Gateway allows only a maximum size of 128kb of data to be sent across 4 x 32kb frames when using Websockets:

    https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html

    I would love it if this package allowed me to specify the maximum frame size somewhere and then it would automatically split up messages and re-combine them on the other side to overcome this.

    opened by rsshilli 5
  • Still reconnecting after close()

    Still reconnecting after close()

    I just tested v2.0.5 and unfortunately the issue is still there. This is my scenario:

    1. Open WS connection A.
    2. Close WS connection A.
    3. Open WS connection B.
    4. Close WS connection B.
    5. Open WS connection C.

    After a while WS connections A and B are reopened. They are initially closed, but re-opened.

    opened by raduciobanu22 5
  • Add Node.js support

    Add Node.js support

    Currently Sockette depends on a global WebSocket constructor, which is not the case when used on Node.js.

    This PR adds options.WebSocket to allow passing a custom WebSocket constructor, for example from the ws module.

    opened by valeriangalliat 5
  • `self` is not necessary

    `self` is not necessary

    Arrow functions don't create a binding, and a quick look over the code doesn't show a single instance where the difference in bindings would matter. Every instance of this can be replaced with self.

    opened by jhpratt 4
  • Put an option to always reconnect, no matter what

    Put an option to always reconnect, no matter what

    I had to undo the 1000,1001,1005 exceptions in the onClose method. Some reverse proxies like Caddy close the ws with 1001 if you stop/start them, it's so it's annoying having to refresh the page at each reboot or simply reverse proxy config change. Please add an option where you bypass the 1000,1001,1005 check, some application want to keep retrying no matter what.

    onclose: e => {
      console.log(`Closed with code: ${e.code}`);
      if (e.code === 1e3 || e.code === 1001 || e.code === 1005) {
        this.ws.reconnect(e);
      }            
    },
    
    opened by gigitalz 0
  • Change initial Sockette.timer value from 1 to -1

    Change initial Sockette.timer value from 1 to -1

    This PR fixes the issue described in #66 by setting timer value to -1 which would still enable normal functionality of Sockette.reconnect, but at the same time, it will not by mistake clear any other timeouts/intervals.

    Closes #66

    opened by stevium 0
  • Sockette.close can unexpectedly clear other timeouts/intervals

    Sockette.close can unexpectedly clear other timeouts/intervals

    Since the first call to window.setTimeout or window.setInterval is returning handle with ID 1 calling Sockette.close would unexpectedly clear that timeout, because timer=1 is still a valid handle ID.

    opened by stevium 0
  • Update url param to be dynamic if needed

    Update url param to be dynamic if needed

    As requested by issue #59 my use case is the same. I need to pass a token on every connection attempt and it's only possible to use the token once. So the url must change on every reconnect attempt.

    If url param is a function invoke it passing the attempt number

    Solution: Change the url param to be of type:

    - string
    - Promise<string>
    - (attempt: number) => Promise<string>
    - (attempt: number) => string
    

    So the usage would look like:

    // string as it is now
    new Sockette('wss://address')
    // promise style. just adding the setTimeout to simulate
    new Sockette(new Promise((resolve) => {
      setTimeout(() => {
        resolve('wss://address')
      }, 5000)
    }))
    
    new Sockette(Promise.resolve('wss://address'))
    
    new Sockette((attempt) => `wss://address?attempt${attempt}`)
    
    new Sockette(async (attempt) => await Promise.resolve(`wss://address?attempt${attempt}`))
    
    opened by Gabiras12 4
  • [Feature] Ability to set url before reconnecting

    [Feature] Ability to set url before reconnecting

    Right now in order to change websocket url you have to create a new instance of Sockette. This an issue for us because our url includes authorization token which expires after some time and when Sockette tries to reconnect it tries to reconnect using an expired token.

    Here are a couple of possible solutions to this issue:

    1. getUrl config which can be set to a function which either returns a string directly or a Promise<string>. Sockette would use this function every time it tries to automatically establish websocket connection.
    2. setUrl() method on the Sockette class and ability to set onreconnect config to a function which returns a Promise. Sockette would wait for onreconnect promise to finish before it would try to reestablish connection.

    @lukeed what do you think about it? Do you have any better suggestions?

    opened by hakimio 1
Releases(v2.0.4)
  • v2.0.4(Dec 10, 2018)

  • v2.0.3(Nov 14, 2018)

    Patches

    • Add default protocols for Firefox (#20): a465457 Thanks @Inva0!

    • Allow reconnect() to continue when no connection can establish on init (#30): 14424e4

    • Ensure code=1005 default when close()ing without arguments (#36): 5102793, d935a48

    Chores

    • Shaving yaks & code-golfing for 24 bytes (15 net) savings: e2ffefd, 8d0bcd6, c8c8d91
    Source code(tar.gz)
    Source code(zip)
  • v2.0.2(Nov 13, 2018)

    Features

    • NEW The sockette UMD build is now available on unpkg.com 🎉

      Check it out: https://unpkg.com/sockette

    Patches

    • Use .mjs extension for ES Module entry: bc08862

    Chores

    • Update README badges & size: 5adf646, 67c9686
    • Update build tools: 96fec8b
    Source code(tar.gz)
    Source code(zip)
  • v2.0.1(Nov 13, 2018)

    Patches

    • Add json() to README (#26): 9df3e08 Thanks @mehmetkose!

    • Included type definitions (#27): f3be7f2 Thanks @PatrickSachs!

    • Fix typo in README (#33): ce834f0

    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Feb 12, 2018)

    Breaking

    • You must now instantiate an instance rather than functional helper: 0a9c339

      const Sockette = require('sockette');
      
      // Don't:
      let ws = Sockette('...');
      
      // Do:
      let ws = new Sockette('...');
      
    • Sockette no longer returns the underlying WebSocket: 0a9c339

      Instead, it returns itself, keeping the current WebSocket instance protected and out of reach.

      Returning the WebSocket prevented the ability to send new messages after successful reconnects.

    Minor

    • NEW: Added opts.onmaximum callback (#11): 712defb, e59b0e7

      This is called when the maxAttempts have been exhausted.

    Patches

    • Fixed transmits from Sockette after reconnecting/recovering from failure: 0a9c339

      By hiding the underlying WebSocket, Sockette can safely swap/update instances without invalidating your pointer to initial WebSocket return.

    • A successful reconnection will reset the tracked attempts count: 6d8095a

      Previously, reconnecting after 6 attempts only left you 4 attempts for your next connection failure — assuming a limit of 10.

    • Update README docs: b9d74b0, e656e08, 556fe3e, e59b0e7

    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Feb 1, 2018)

    Minor Changes

    • Added new json() convenience method (#4): f3f0bbd

      Auto-casts payload to string (via JSON.stringify). Thanks @bl4ckm0r3! 🎉

    Patches

    • Update docs for json() addition: 117f06d
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Jan 31, 2018)

    Minor Changes

    • Don't auto-enforce a close(1000): f8771f0

      As @lpinca pointed out, this is non-compliant behavior to the WS spec, and I was porting/pulling too much from personal use cases.

    Patches

    • Accept 1005 code as normal closure event (#3): f8771f0

      Thanks @lpinca!

    • Update docs: ea94336, 3a03dc5

    Source code(tar.gz)
    Source code(zip)
Owner
Luke Edwards
Luke Edwards
A node.js module for websocket server and client

Nodejs Websocket A nodejs module for websocket server and client How to use it Install with npm install nodejs-websocket or put all files in a folder

Guilherme Souza 719 Dec 13, 2022
A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

WebSocket Client & Server Implementation for Node Overview This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and

Brian McKelvey 3.6k Dec 30, 2022
WebSocket emulation - Node.js server

SockJS-node SockJS for enterprise Available as part of the Tidelift Subscription. The maintainers of SockJS and thousands of other packages are workin

SockJS 2.1k Dec 29, 2022
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

ws: a Node.js WebSocket library ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Passes the quit

WebSockets 19.2k Jan 4, 2023
Standards-compliant WebSocket client and server

faye-websocket This is a general-purpose WebSocket implementation extracted from the Faye project. It provides classes for easily building WebSocket s

null 588 Dec 23, 2022
Lightweight WebSocket lib with socket.io-like event handling, requests, and channels

ws-wrapper Lightweight and isomorphic Web Socket lib with socket.io-like event handling, Promise-based requests, and channels. What? Much like Socket.

Blake Miner 70 Dec 23, 2022
A Develop Tool to Test WebSocket, Socket.IO, Stomp, Bayeux, HTTP, TCP, UDP, WebRTC, DNS API.

A Develop Tool to Test WebSocket, Socket.IO, Stomp, Bayeux, HTTP, TCP, UDP, WebRTC, DNS API.

York Yao 24 Sep 6, 2022
WebSocket cat

WebSocket cat

WebSockets 1.6k Jan 2, 2023
How to build a chat using Lambda + WebSocket + API Gateway? (nodejs)

Description Source code for the lambda function from the screencast How to build a chat using Lambda + WebSocket + API Gateway? (nodejs) The reactjs c

Alex 21 Dec 28, 2022
Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js

CHAT-APP-WEBSOCKET Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js Obs o intuito deste projeto não é o fronten

Vinicius dos Santos Rodrigues 4 Jul 14, 2022
A tiny Nuxt.js module for WebSocket interactions

@deepsource/nuxt-websocket A tiny Nuxt.js module for WebSocket interactions. This module is only compatible with Nuxt v2 at the moment. Setup Add @dee

DeepSource 23 Dec 6, 2022
A websocket-based reverse shell for XSS attacks.

CrossSiteShell A javascript/nodejs "reverse shell" that makes it easier to interact with the victim's browser during XSS attacks. Usage Run the follow

Rafael 13 Oct 7, 2022
Um bot feito utilizando a API baileys em WebSocket para o Whatsapp Multi-Devices.

Informação ?? O BaileysBot foi feito utilzando a API Baileys Caso encontre algum BUG, faça um Novo Issue! Requisitos ?? NodeJS Git Instalação ?? Para

null 12 Dec 3, 2022
This Repository implements an Authenticated Websocket Server built in Node Js along ws library.

websockets-authentication-server This Repository implements an Authenticated Websocket Server built in Node Js along ws library. Features Authenticate

M.Abdullah Ch 7 May 5, 2023
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
it is websocket-store for using easily websocket

Socket-Store It is Websocket Store How to use 1. Install # npm npm install socket-store # yarn yarn add socket-store 2. Create MessageHandler and

nerdchanii 4 Sep 13, 2022
Lightweight WebSocketServer wrapper lib using ws-wrapper to wrap connected WebSockets

ws-server-wrapper Lightweight WebSocketServer wrapper lib using ws-wrapper and ws to wrap connected WebSockets. The only dependency is ws-wrapper itse

Blake Miner 17 May 9, 2022
Easy-to-use React component for websocket communications.

react-websocket react-websocket is a easy-to-use React component for websocket communications. Help Wanted Things here are running very slowly as I ha

Mehmet Kose 349 Sep 14, 2022
Full-featured, middleware-oriented, programmatic HTTP and WebSocket proxy for node.js

rocky A multipurpose, full-featured, middleware-oriented and hackable HTTP/S and WebSocket proxy with powerful built-in features such as versatile rou

Tom 370 Nov 24, 2022
A simple NodeJS WebSocket WebApp vulnerable to blind SQL injection

NodeJS WebSocket SQLi vulnerable WebApp A one-day build of a vulnerable WebSocket app on NodeJS to practice boolean based SQLi over WebSocket. I made

Rayhan Ahmed 36 Dec 27, 2022