Socket
Socket
Sign inDemoInstall

promise-ws

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

promise-ws

A Promise-Based WebSocket implementation for Node.js


Version published
Weekly downloads
5.1K
decreased by-12.04%
Maintainers
1
Weekly downloads
 
Created
Source

promise-ws

Build Status CircleCI Build status Coverage Status PRs Welcome License

A promise based WebSocket implementation for Node.js. Built on top of ws

Table of Contents

Usage

import { Server, Client } from "promise-ws";

(async function main() {
  const port = 3000;
  const server = await Server.create({ port });
  server.reply("say", async data => {
    console.log("data"); /* 'hello' */
    return "world";
  });

  const url = `ws://127.0.0.1:${port}`;
  await Client.autoReconnect(url, async client => {
    const response = await client.request("say", "hello");
    console.log(response); /* 'world' */
  });
})();

Installation

$ npm install promise-ws

API Reference

Server.create(options)

Arguments
  1. options <Object>: All options will be passed to WebSocket.Server(opsions), except for clientTracking, which will always be true.
Returns
  • server <Promise<Server>>

Create a WebSocket server

Server Events

Server extends EventEmitter, which forwards these events from WebSocket.Server:

server#onConnection(callback)

  1. callback <Function>: The callback function, the only argument is client.

Like server.on('connection', callback), the only difference is the callback argument is client but not ws.

server#onReply(name, response)

  1. name <String>: The name of the event
  2. response <Function>: The callback function. Should return a promise

Add a reply function. Will be called when client calls request(). The response function arguments are the same with client.request(name, ...arguments) arguments. The returning value in response would be reply to the issuer client request function.

server#addReply(name, response)

Alias for server#onReply(name, response)

server#reply(name, response)

Alias for server#onReply(name, response)

server#removeReply(name, response)

  1. name <String>: The name of the event
  2. response <Function>: The callback function

Remove a reply function.

server#replyCount(name)

  1. name <String>: The name of the event

Get reply function count by name.

server#request(name[, ...args])

Arguments
  1. name <String>: The name of the event
  2. ...args <Any>: The request arguments
Returns
  • responseArray <Promise[<Any>]/>: Response array by clients replied

Request to all clients and wait for reply.

server#wss()

Returns

Get <WebSocket.Server> instance.

server#close()

Returns
  • <Promise>

Stops the server.

server#clients

The connected clients.


Client.create(address[, options])

Arguments
  1. address <String>: The address/URL to which to connect
  2. options <Object>
  • onClose <Function>: The callback function when client closed
Returns
  • client <Promise<Client>>

Create a WebSocket client.

Example
import { Client } from "promise-ws";

(async function main() {
  const client = await Client.create("ws://127.0.0.1:3000", {
    onClose() {
      console.error("server closed");
    }
  });
  /* do something... */
})();

Client.connect(address, waitUntil)

Arguments
  1. address <String>: The address/URL to which to connect
  2. waitUntil <Function>: The main function to handle client. Should return a promise
Returns
  • <Promise<Any>>

Create a WebSocket client and pass to the first argumet of waitUntil function.

The waitUntil function will keep running until one of these reasons:

  • The waitUntil function returns a value. The value will be returned to Client.connect() as a promise
  • The waitUntil function throws an error. This will throw a rejection
  • The server closed. This will throw a rejection, and the error message will be "CLOSE"
Example
import { Client } from "promise-ws";

(async function main() {
  try {
    const url = "ws://127.0.0.1:3000";
    const res = await Client.connect(url, async client => {
      /* do something... */
      return "chris";
    });
    console.log("res:", res); /* res: chris */
  } catch (err) {
    if (err.message === "CLOSE") {
      console.error("server closed");
    } else {
      console.error(err);
    }
  }
})();

Client.autoReconnect(address, waitUntil[, delay])

Arguments
  1. address <String>: The address/URL to which to connect
  2. waitUntil <Function>: The main function to handle client. Should return a promise
  3. delay <Number>: Delay time before reconnect in ms. Defaults to 1000
Returns
  • <Promise<Any>>

Like Client.connect(), but if server closed, it will never throw error, and it will try to reconnect to the server after delay.

Example
import { Client } from "promise-ws";

(async function main() {
  try {
    const url = "ws://127.0.0.1:3000";
    const res = await Client.autoReconnect(url, async client => {
      /* do something... */
      return "chris";
    });
    console.log("res:", res); /* res: chris */
  } catch (err) {
    console.error(err);
  }
})();

Client Events

Client extends EventEmitter, which forwards these events from WebSocket.Client:

client#onReply(name, response[, errorHandler])

  1. name <String>: The name of the event
  2. response <Function>: The callback function. Should return a promise
  3. errorHandler <Function>: The error handler function

Add a reply function. Will be called when server calls request(). The response function arguments are the same with server.request(name, ...arguments) arguments. The returning value in response would be reply to the server request function.

client#addReply(name, response[, errorHandler])

Alias for client#onReply(name, response)

client#reply(name, response[, errorHandler])

Alias for client#onReply(name, response)

client#removeReply(name, response[, errorHandler])

  1. name <String>: The name of the event
  2. response <Function>: The callback function

Remove a reply function.

client#replyCount(name)

  1. name <String>: The name of the event

Get reply function count by name.

client#request(name[, ...args])

Arguments
  1. name <String>: The name of the event
  2. ...args <Any>: The request arguments
Returns
  • responseData <Promise<Any>/>: Response data by server replied

Request to all clients and wait for reply.

client#requestClose()

Request to close server, will return a promise to wait for completion.

client#ws()

Returns

Get <WebSocket.Client> instance.

client#close()

Stops the client.

License

MIT

Keywords

FAQs

Package last updated on 21 Apr 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc