ws-sockette
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

Welcome to ws-sockette 👋

Version License: MIT Twitter: jellydn

The little WebSocket wrapper for nodejs

Install

yarn add ws-sockette

Why

Sockette is a tiny (367 bytes) wrapper around WebSocket that will automatically reconnect if the connection is lost!

However, sockette doesn't work for nodejs and missing support for client options for create a websocket client

new WebSocket(
        address: string | URL,
        protocols?: string | string[],
        options?: WebSocket.ClientOptions | ClientRequestArgs,
    );

That's why I take a chance to rewrite with typescript and support nodejs. If you need a tiny wrapper for browser, please use sockette.

Usage

import { wsSockette } from "ws-sockette";

const ws = wsSockette("ws://localhost:3000", {
  clientOptions: {
    headers: {
      Authorization: "Basic YWxhZGRpbjpvcGVuc2VzYW1l",
    },
  },
  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

interface SocketteOptions {
  // This is a new option if you compare with sockette
  clientOptions?: WebSocket.ClientOptions | ClientRequestArgs;

  protocols?: string | string[];
  timeout?: number;
  maxAttempts?: number;
  onopen?: (ev: WebSocket.Event) => any;
  onmessage?: (ev: WebSocket.MessageEvent) => any;
  onreconnect?: (ev: WebSocket.ErrorEvent | WebSocket.CloseEvent) => any;
  onmaximum?: (ev: WebSocket.ErrorEvent | WebSocket.CloseEvent) => any;
  onclose?: (ev: WebSocket.CloseEvent) => any;
  onerror?: (ev: WebSocket.ErrorEvent) => any;
}

Please check here for complete document

Run tests

yarn test

Author

👤 Huynh Duc Dung

Show your support

Give a ⭐️ if this project helped you!


This README was generated with ❤️ by readme-md-generator

Readme

Keywords

none

Package Sidebar

Install

npm i ws-sockette

Weekly Downloads

1

Version

0.2.0

License

MIT

Unpacked Size

348 kB

Total Files

16

Last publish

Collaborators

  • jellydn