Lightweight WebSocketServer wrapper lib using ws-wrapper to wrap connected WebSockets

Overview

ws-server-wrapper

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

Install

npm install ws-server-wrapper

Usage

See ws-wrapper README or the API documentation below for more details.

Quick Server-side Example:

Use ws-server-wrapper to wrap the WebSocket.Server:

const WebSocketServer = require("ws").Server
	, WebSocketServerWrapper = require("ws-server-wrapper");
var wss = new WebSocketServer({port: 3000});
var serverWrapper = new WebSocketServerWrapper(wss);
// Send "msg" event to all connected clients
serverWrapper.emit("msg", "Hello!");
// For all connected clients, listen for the "ping" request on the channel "pointless"
serverWrapper.of("pointless").on("ping", function() {
  // `this` refers to the "pointless" channel for the socket who sent the "ping" request
  // Let's just respond to the request with the value "pong"
  return "pong";
});

API

Class: WebSocketServerWrapper

A WebSocketServerWrapper simply wraps around a WebSocket.Server to give you well-deserved functionality. :)

server = new WebSocketServerWrapper(webSocketServerInstance[, options]);

Constructs a new WebSocketServerWrapper, and binds it to the native WebSocketServer instance from ws.

  • webSocketServerInstance - the native WebSocketServer instance
  • options - options passed to each WebSocketWrapper constructor when a WebSocket connects. See the ws-wrapper API for details.
    • requestTimeout - See the ws-wrapper API API for more info. Defaults to 2 minutes if not specified.
    • heartbeatInterval - If set, a "ping" will be sent to all connected sockets every heartbeatInterval milliseconds. If a "pong" response is not received by the start of the next ping, the connection will be terminated. Defaults to 1 minute if not specified. Set to a falsy value to disable heartbeats.

Events

  • Event: "connection" - Emitted when a WebSocket connects to the WebSocketServer
    • socket - A WebSocketWrapper instance, wrapping a native WebSocket
    • request - A http.IncomingMessage instance.
  • Event: "disconnect" - Emitted when a WebSocket disconnects from the WebSocketServer
    • socket - A WebSocketWrapper instance, wrapping a native WebSocket
  • Event: "error" - Emitted when an error occurs on the WebSocketServer
    • err

The EventEmitter-like API looks like this:

See the ws-wrapper API documentation for more details.

  • server.on(eventName, listener) Adds the listener function to the end of the listeners array for the event named eventName for all connected sockets, now and in the future. When an event or request matching the eventName is received by any connected WebSocket, the listener is called.

    Values returned by the listener callback are used to respond to requests. If the return value of the listener is a Promise, the response to the request will be sent once the Promise is resolved or rejected; otherwise, the return value of the listener is sent back to the remote end immediately.

    If the inbound message is a simple event (not a request), the return value of the listener is ignored.

  • server.removeListener(eventName, listener) Removes the specified listener from the listener array for the event named eventName.

  • server.removeAllListeners([eventName]) Removes all listeners, or those of the specified eventName.

  • server.eventNames() Returns an array listing the events for which the emitter has registered listeners.

  • server.listeners(eventName) Returns a copy of the array of listeners for the event named eventName.

  • server.emit(eventName[, ...args]) Sends an event to all connected WebSockets with the specified eventName calling all listeners for eventName on the remote end, in the order they were registered, passing the supplied arguments to each.

Note: server.once() and server.request() are not supported at this time.

Channel API:

  • server.of(channelName) Returns the channel with the specified channelName. Every channel has the same EventEmitter-like API as described above for sending and handling channel-specific events for all connected sockets.

Other methods and properties:

  • server.sockets - A Set of connected WebSocketWrappers.
  • server.close() Closes the native WebSocketServer

Detecting Broken Connections

The WebSocketServerWrapper will automatically (by default) ping all open sockets on a regular basis. If there is no "pong" response by the start of the next ping, the connection will be assumed to be "broken" and will be terminated automatically.
See options.heartbeatInterval for more information. Also see the approached outlined here.

You might also like...

Lab demonstrating how to share sensitive data, using Basis Theory tokenization.

sendsecure.ly A Basis Theory Lab that enables users to securely share passwords, credentials, or any other sensitive data with another person. The app

Dec 29, 2022

:ledger: Minimal lightweight logging for JavaScript, adding reliable log level methods to wrap any available console.log methods

loglevel Don't debug with logs alone - check out HTTP Toolkit: beautiful, powerful & open-source tools for building, testing & debugging HTTP(S) Minim

Jan 6, 2023

The leaderboard website displays scores submitted by different players. It also allows you to submit your score. I created this project using ES6 concepts. I connected to the Leadboard API service

Leaderboard App The leaderboard website displays scores submitted by different players. It also allows you to submit your score I created this project

Dec 21, 2022

Blaze is a file sharing progressive web app built using WebTorrent and WebSockets

Blaze is a file sharing progressive web app built using WebTorrent and WebSockets

Blaze is a file sharing progressive web app(PWA) that allows users to transfer files between multiple devices. I

Jan 4, 2023

A template for WebSockets powered Cloudflare Worker project using graphql-ws

🚡 graphql-ws on Cloudflare Workers A template for WebSockets powered Cloudflare Worker project using graphql-ws. The worker serves the following rout

Dec 18, 2022

Wrap native HTTP requests with RFC compliant cache support

cacheable-request Wrap native HTTP requests with RFC compliant cache support RFC 7234 compliant HTTP caching for native Node.js HTTP/HTTPS requests. C

Dec 20, 2022

Wrap selected text in custom tags with shortcuts.

Wrap selected text in custom tags with shortcuts.

Obsidian Wrap With Shortcuts Wrap the selected text in customized tags with shortcuts. Underline is provided with Ctrl-u(Cmd-u) as default wrappers. P

Dec 28, 2022

Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called

bun-livereload Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called. import liveRelo

Dec 19, 2022

Wrap zod validation errors in user-friendly readable messages

zod-validation-error Wrap zod validation errors in user-friendly readable messages. Features User-friendly readable messages, configurable via options

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.

Dec 23, 2022

A status monitor for Elite Dangerous, written in PHP. Designed for 1080p screens in the four-panel-view in panel.php, and for 7 inch screens with a resolution of 1024x600 connected to a Raspberry Pi.

EDStatusPanel A status monitor for Elite Dangerous, written in PHP. Designed for 1080p screens in the four-panel-view in panel.php, and for 7 inch scr

Oct 4, 2022

Remote Code Execution V1 For iOS 15 sent through airdrop after the device was connected to a trusted host

Remote Code Execution V1 For iOS 15 sent through airdrop after the device was connected to a trusted host

iOS 15.0.1 RCE V1 Author: Jonathan Scott @jonathandata1 Date: October 9th, 2021 Release Version 1.0 Description When an iOS device has been connected

Dec 26, 2022

Utility for authorizing user in a connected app, creating JWT to authenticate against it, and perform a sample callout.

Question: What is this for? Answer: When configuring a Salesforce Connected app to use certificates to authenticate you will use JSON Web Tokens to a

Jun 15, 2022

Omnichannel Live Chat Widget UI Components offers a re-usable component-based library to help create a custom chat widget that can be connected to the Dynamics 365 Customer Service experience.

Omnichannel Live Chat Widget UI Components @microsoft/omnichannel-chat-widget is a React-based UI component library which allows you to build your own

Dec 15, 2022

Get a verse(an aya) from the Quran during your coding session 💻 , stay connected with the words of Allah. 🕋

Get a verse(an aya) from the Quran during your coding session 💻 , stay connected with the words of Allah. 🕋

Ayat 📝 Get a verse(an aya) from the Quran during your coding session 💻 stay connected with the words of Allah. 💚 🕋 Release Notes 1.0.0 Get random

Jan 2, 2023

Talk to anyone connected to your network, be it LAN or your hotspot. Doesn't require internet.

Talk to anyone connected to your network, be it LAN or your hotspot. Doesn't require internet.

Apophis CLI to talk to anyone connected to your network, be it LAN or your hotspot. Doesn't require internet. Installation Make sure you have NodeJS (

Oct 16, 2022

A Promise-based API for WebSockets

A Promise-based API for WebSockets

websocket-as-promised A WebSocket client library with Promise-based API for browser and Node.js. Example import WebSocketAsPromised from 'websocket-as

Dec 18, 2022

JSON-RPC 2.0 implementation over WebSockets for Node.js and JavaScript/TypeScript

JSON-RPC 2.0 implementation over WebSockets for Node.js and JavaScript/TypeScript

WebSockets for Node.js and JavaScript/TypeScript with JSON RPC 2.0 support on top. About The rpc-websockets library enables developers to easily imple

Dec 21, 2022
Comments
  • Proposal to support native ping pong out of the box

    Proposal to support native ping pong out of the box

    Hi @bminer,

    I would like to thank you for this nice repo and to propose to add ping pong out of the box like here:

    https://github.com/websockets/ws#how-to-detect-and-close-broken-connections

    what you think about that?

    opened by ogheo 6
  • Equivalent function to socket.join ?

    Equivalent function to socket.join ?

    I was using SocketIO but I still wanted more performance for my game actions (store, rooms, inventory and etc), so I discovered this wonderful library and your work on that project that is very good.

    I wanted something similar to the "socket.join" function because I need to send information only to people connected in that room (and I also believe that this way would not send unnecessary packet to other clients that are not in the room, room ids are dynamically generated)

    I looked in the documentation and did not find anything that would serve this, sorry if I'm wrong

    Sorry for any inconvenience

    opened by FifineHex 2
  • handleUpgrade support

    handleUpgrade support

    does it support handleUpgrade method? see example here: https://github.com/websockets/ws#multiple-servers-sharing-a-single-https-server

    should i use wrapper.server.handleUpgrade? It seems this is working this way, but I have some problems and not sure if that's related to supporting this method.

    Please advice.

    opened by anotheri 1
  • cache modConcat output

    cache modConcat output

    I wrote a routine called concatAndCache() for use in server.js in the example app. The routine caches the output of modConcat and only regenerates when necessary.

    opened by BenjaminPritchard 1
Owner
Blake Miner
Blake Miner
A Promise-based API for WebSockets

websocket-as-promised A WebSocket client library with Promise-based API for browser and Node.js. Example import WebSocketAsPromised from 'websocket-as

Vitaliy Potapov 547 Dec 18, 2022
JSON-RPC 2.0 implementation over WebSockets for Node.js and JavaScript/TypeScript

WebSockets for Node.js and JavaScript/TypeScript with JSON RPC 2.0 support on top. About The rpc-websockets library enables developers to easily imple

Elpheria 482 Dec 21, 2022
simple chat app created with nextjs, express, tailwindcss, and WebSockets

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Erfan Hanifezade 10 Sep 10, 2022
soketi is your simple, fast, and resilient open-source WebSockets server

soketi soketi is your simple, fast, and resilient open-source WebSockets server. ?? Blazing fast speed ⚡ The server is built on top of uWebSockets.js

Soketi 3.2k Jan 4, 2023
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
The cutest little WebSocket wrapper! 🧦

Sockette The cutest little WebSocket wrapper! ?? Sockette is a tiny (367 bytes) wrapper around WebSocket that will automatically reconnect if the conn

Luke Edwards 2.4k Jan 2, 2023
Create a Real-time Chat App using React and Socket.io

React And Socket.io ChatApp MIT Licence MIT License Copyright (c) 2021 Ali Ahmad Permission is hereby granted, free of charge, to any person obtaining

Ali Ahmad 2 Jan 10, 2022
Sse-example - SSE (server-sent events) example using Node.js

sse-example SSE (server-sent events) example using Node.js SSE is a easy way to commutate with the client side in a single direction. it has loss cost

Jack 2 Mar 11, 2022
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
Full-Stack Instgram Clone using MERN Stack and Socket.io

Instagram MERN Full-Stack Instgram Clone using MERN Stack and Socket.io Visit Now ?? ??️ Tech Stack Frontend: Backend: Realtime Communication: Cloud S

Jigar Sable 326 Dec 27, 2022