promise-ws
![License](https://img.shields.io/badge/license-MIT_License-blue.svg?style=flat)
A promise based WebSocket implementation for Node.js. Built on top of ws
Table of Contents
- Usage
- Installation
- API Reference
- Server.create(options)
- Server Events
- server#onReply(name, response)
- server#addReply(name, response)
- server#reply(name, response)
- server#removeReply(name, response)
- server#replyCount(name)
- server#request(name[, ...args])
- server#wss()
- server#close()
- server#clients
- Client.create(address[, options])
- Client.connect(address, waitUntil)
- Client.autoReconnect(address, waitUntil[, delay])
- Client Events
- client#onReply(name, response)
- client#addReply(name, response)
- client#reply(name, response)
- client#removeReply(name, response)
- client#replyCount(name)
- client#request(name[, ...args])
- client#ws()
- client#close()
- License
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');
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);
});
}());
Installation
$ npm install promise-ws
API Reference
Server.create(options)
Arguments
options
<Object>: All options will be passed to WebSocket.Server(opsions), except for clientTracking
, which will always be true
.
Returns
Create a WebSocket server
Server Events
Server extends EventEmitter, which forwards these events from WebSocket.Server:
server#onReply(name, response)
name
<String>: The name of the eventresponse
<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)
name
<String>: The name of the eventresponse
<Function>: The callback function
Remove a reply function.
server#replyCount(name)
name
<String>: The name of the event
Get reply function count by name.
server#request(name[, ...args])
Arguments
name
<String>: The name of the event...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
Stops the server.
server#clients
The connected clients.
Client.create(address[, options])
Arguments
address
<String>: The address/URL to which to connectoptions
<Object>
onClose
<Function>: The callback function when client closed
Returns
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'); }
});
}());
Client.connect(address, waitUntil)
Arguments
address
<String>: The address/URL to which to connectwaitUntil
<Function>: The main function to handle client. Should return a promise
Returns
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) => {
return 'chris';
});
console.log('res:', res);
}
catch (err) {
if (err.message === 'CLOSE') { console.error('server closed'); }
else { console.error(err); }
}
}());
Client.autoReconnect(address, waitUntil[, delay])
Arguments
address
<String>: The address/URL to which to connectwaitUntil
<Function>: The main function to handle client. Should return a promisedelay
<Number>: Delay time before reconnect in ms. Defaults to 1000
Returns
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) => {
return 'chris';
});
console.log('res:', res);
}
catch (err) {
console.error(err);
}
}());
Client Events
Client extends EventEmitter, which forwards these events from WebSocket.Client:
client#onReply(name, response)
name
<String>: The name of the eventresponse
<Function>: The callback function. Should return a promise
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)
Alias for client#onReply(name, response)
client#reply(name, response)
Alias for client#onReply(name, response)
client#removeReply(name, response)
name
<String>: The name of the eventresponse
<Function>: The callback function
Remove a reply function.
client#replyCount(name)
name
<String>: The name of the event
Get reply function count by name.
client#request(name[, ...args])
Arguments
name
<String>: The name of the event...args
<Any>: The request arguments
Returns
responseData
<Promise<Any>/>: Response data by server replied
Request to all clients and wait for reply.
client#ws()
Returns
Get <WebSocket.Client> instance.
client#close()
Stops the client.
License
MIT