Gathering detailed insights and metrics for websocket-ts
Gathering detailed insights and metrics for websocket-ts
Gathering detailed insights and metrics for websocket-ts
Gathering detailed insights and metrics for websocket-ts
npm install websocket-ts
Typescript
Module System
Node Version
NPM Version
88
Supply Chain
99.6
Quality
75.6
Maintenance
100
Vulnerability
100
License
TypeScript (100%)
Love this project? Help keep it running — sponsor us today! 🚀
Total Downloads
459,349
Last Day
1,502
Last Week
7,680
Last Month
29,369
Last Year
221,550
MIT License
120 Stars
178 Commits
20 Forks
2 Watchers
3 Branches
1 Contributors
Updated on Feb 03, 2025
Minified
Minified + Gzipped
Latest Version
2.1.5
Package Id
websocket-ts@2.1.5
Unpacked Size
244.92 kB
Size
33.82 kB
File Count
131
NPM Version
9.5.0
Node Version
18.15.0
Published on
Oct 08, 2023
Cumulative downloads
Total Downloads
Last Day
9.8%
1,502
Compared to previous day
Last Week
11.7%
7,680
Compared to previous week
Last Month
38.1%
29,369
Compared to previous month
Last Year
39.7%
221,550
Compared to previous year
Install websocket-ts
with npm:
1$ npm install websocket-ts
This example shows how to use the package, complete with message buffering and automatic reconnection. The created websocket will echo back any received messages. It will buffer messages when disconnected and attempt to reconnect every 1 second.
1import { 2 ArrayQueue, 3 ConstantBackoff, 4 Websocket, 5 WebsocketBuilder, 6 WebsocketEvent, 7} from "websocket-ts"; 8 9// Initialize WebSocket with buffering and 1s reconnection delay 10const ws = new WebsocketBuilder("ws://localhost:8080") 11 .withBuffer(new ArrayQueue()) // buffer messages when disconnected 12 .withBackoff(new ConstantBackoff(1000)) // retry every 1s 13 .build(); 14 15// Function to output & echo received messages 16const echoOnMessage = (i: Websocket, ev: MessageEvent) => { 17 console.log(`received message: ${ev.data}`); 18 i.send(`echo: ${ev.data}`); 19}; 20 21// Add event listeners 22ws.addEventListener(WebsocketEvent.open, () => console.log("opened!")); 23ws.addEventListener(WebsocketEvent.close, () => console.log("closed!")); 24ws.addEventListener(WebsocketEvent.message, echoOnMessage);
This will demonstrate how to use websocket-ts
in your project using the provided WebsocketBuild
-class.
For a more detailed description of the API, please refer to the API Documentation.
Create a new instance with the WebsocketBuilder
:
1const ws = new WebsocketBuilder("ws://localhost:42421").build();
There are six events which can be subscribed to through with event listeners:
1export enum WebsocketEvent { 2 open = "open", // Connection opened 3 close = "close", // Connection closed 4 error = "error", // Error-induced closure 5 message = "message", // Message received 6 retry = "retry", // Reconnect attempt 7 reconnect = "reconnect" // Successful reconnect 8}
Event listeners receive the websocket instance (i
) and the triggering event (ev
) as arguments.
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .onOpen((i, ev) => console.log("opened")) 3 .onClose((i, ev) => console.log("closed")) 4 .onError((i, ev) => console.log("error")) 5 .onMessage((i, ev) => console.log("message")) 6 .onRetry((i, ev) => console.log("retry")) 7 .onReconnect((i, ev) => console.log("reconnect")) 8 .build();
To unregister a specific event listener, use removeEventListener
:
1let ws: Websocket 2/* ... */ 3ws.removeEventListener(WebsocketEvent.open, openEventListener);
Use the send
method to send a message to the server:
1let ws: Websocket; 2/* ... */ 3ws.send("Hello World!");
If you'd like the websocket to automatically reconnect upon disconnection, you can optionally provide a Backoff
strategy.
This sets the delay between reconnection attempts. There are three built-in Backoff
implementations, or you can create
your own by implementing the Backoff
interface. If no Backoff is provided, the websocket will not attempt to reconnect.
The ConstantBackoff
strategy enforces a fixed delay between each reconnection attempt.
To set a constant 1-second wait time, use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBackoff(new ConstantBackoff(1000)) // 1000ms = 1s 3 .build();
The LinearBackoff
strategy increases the delay between reconnection attempts linearly,
up to an optional maximum. For example, to start with a 0-second delay and increase by
10 second for each retry, capping at 60 seconds, use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBackoff(new LinearBackoff(0, 10000, 60000)) // 0ms, 10s, 20s, 30s, 40s, 50s, 60s 3 .build();
The ExponentialBackoff
strategy doubles the delay between each reconnection attempt, up
to a specified maximum. This approach is inspired by the binary exponential backoff algorithm
commonly used in networking. For example, to generate a backoff series like [1s, 2s, 4s, 8s]
, use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBackoff(new ExponentialBackoff(1000, 6)) // 1s, 2s, 4s, 8s, 16s, 32s, 64s 3 .build();
To buffer outgoing messages when the websocket is disconnected, you can optionally specify
a Queue
. This queue will temporarily store your messages and send them in sequence when
the websocket (re)connects. Two built-in Queue
implementations are available, or you can
create your own by implementing the Queue
interface. If no queue is provided, messages
won't be buffered.
The RingQueue
is a fixed-capacity, first-in-first-out (FIFO) queue. When it reaches capacity,
the oldest element is removed to accommodate new ones. Reading from the queue returns and
removes the oldest element. For instance, to set up a RingQueue
with a 100-element capacity,
use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBuffer(new RingQueue(100)) 3 .build();
The ArrayQueue offers an unbounded capacity, functioning as a first-in-first-out (FIFO) queue.
Reading from this queue returns and removes the oldest element. To use an ArrayQueue
, use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBuffer(new ArrayQueue()) 3 .build();
To compile the project, execute npm run build
. The codebase includes unit tests for all
components. To run these tests, use npm run test
.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 0/19 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
Project has not signed or included provenance with any releases.
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-02-10
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn Moremicrosoft-cognitiveservices-speech-sdk
Microsoft Cognitive Services Speech SDK for JavaScript
light-websocket-client-ts
轻量 Websocket 封装
tsrpc
A TypeScript RPC Framework, with runtime type checking and built-in serialization, support both HTTP and WebSocket.
node-napcat-ts
napcat SDK for Node