@clusterws/cws

中文文档
3.0.0发布于 2020/07/04MITTypeScriptCommonJS零依赖近 30 天下载 2172

cWS - fast C++ WebSocket implementation for Node.js

原始使用文档
文档目录8 节
  1. Important Notes
  2. Supported Node Versions
  3. Documentation
  4. Installation
  5. Websocket Client
  6. Websocket Server
  7. Secure WebSocket
  8. Handle App Level Ping In Browser (example)

ClusterWS/cWS

Fast WebSocket implementation for Node.js

npm version travis build

Important Notes

Supported Node Versions

CWS VersionNode 10Node 11Node 12Node 13Node 14
3.0.0>=10.0X>=12.16>=13.9>=14.5
2.0.0>=10.0X>=12.16>=13.9X
1.6.0>=10.0>=11.0>=12.0 & <12.16>=13.9X

Documentation

Table of Contents

Installation

npm i @clusterws/cws

Websocket Client

Typings: dist/client.d.ts

Import cws WebSocket:

const { WebSocket } = require('@clusterws/cws');

Connect to WebSocket server:

const socket = new WebSocket(/* ws server endpoint **/);

Event on open is triggered when server accepts connection and this connection is ready to perform other actions:

socket.on('open', () => { });
// or like browser interface
socket.onopen = () => { };

Event on error is triggered if there is an error with the connection:

socket.on('error', (err) => { });
// or like browser interface
socket.onerror = (err) => { };

Event on close is triggered when connection has been closed:

// code: number and reason: string are optional
socket.on('close', (code, reason) => { });
// or like browser interface
socket.onclose = (code, reason) => { };

Event on message is triggered when client receives message(s):

// receives string or binary

socket.on('message', (message) => { });
// or like browser interface
socket.onmessage = (message) => { };

Event ping is triggered when other side sends ping to check if connection still active:

socket.on('ping', () => { });

Event pong is triggered after ping has been sent and it received back conformation:

socket.on('pong', () => { })

To send message use send function:

// send accepts string or binary
// will automatically identify type
socket.send(msg);

// will overwrite/specify message type to string (does not transform data to specified type)
socket.send(msg, { binary: false });

// will overwrite/specify message type to binary (does not transform data to specified type)
socket.send(msg, { binary: true });

// will call callback after message sent or errored
socket.send(msg, null, (err) => { });

To close connection you can use close or terminate methods:

// clean close code and reason are optional
socket.close(code, reason);
// destroy socket 
socket.terminate()

Use ping function to manually send ping:

socket.ping();
// now just wait for `pong` event

To get current socket ready state can use readyState getter:

socket.readyState; // -> OPEN (1) or CLOSED (3)

// check if socket open can be done by
if(socket.readyState === socket.OPEN) {}

// check if socket closed can be done by
if(socket.readyState === socket.CLOSED) {}

To get addresses use _socket getter:

socket._socket;

// Returns some thing like (all fields could be undefined):
// {
//  remotePort,
//  remoteAddress,
//  remoteFamily
// }

For more information check typings (*.d.ts) files in dist folder

Websocket Server

Typings: dist/server.d.ts

Import cws WebSocket:

const { WebSocket } = require('@clusterws/cws');

Create WebSocket server:

const wsServer = new WebSocket.Server({ 
  /**
   * port?: number (creates server and listens on provided port)
   * host?: string (provide host if necessary with port)
   * path?: string (url at which accept ws connections)
   * server?: server (provide already existing server)
   * noDelay?: boolean (set socket no delay)
   * noServer?: boolean (use this when upgrade done outside of cws)
   * maxPayload?: number 
   * perMessageDeflate?: boolean | { serverNoContextTakeover: boolean;}
   * verifyClient?: (info: ConnectionInfo, next: VerifyClientNext) => void (use to allow or decline connections)
   **/ 
 }, () => {
  // callback called when server is ready
  // is not called when `noServer: true` or `server` is provided
  // from outside
});

Event on connection is triggered when new client is connected to the server:

// `ws` is websocket client all available options 
// can be found in `Websocket Client` section above
// `req` is http upgrade request
wsServer.on('connection', (ws, req) => {})

Event on error is triggered when server has some issues and noServer is false:

// on error event will NOT include httpServer errors IF
// server was passed under server parameter { server: httpServer },
// you can register on 'error' listener directly on passed server
wsServer.on('error', (err) => { })

Event on close is triggered after you call wsServer.close() function, if cb is provided both cb and on close listener will be triggered:

wsServer.on('close', () => { })

To get all connected clients use clients getter:

wsServer.clients;

// loop thought all clients:
wsServer.clients.forEach((ws) => { });

// get number of clients:
wsServer.clients.length;

To send message to all connected clients use broadcast method:

// broadcast string
wsServer.broadcast(message);

// broadcast binary
wsServer.broadcast(message, { binary: true });

cWS supports auto ping with startAutoPing function:

wsServer.startAutoPing(interval, appLevel);

// send ping to each client every 10s and destroy client if no pong received 
wsServer.startAutoPing(10000);

// pass true as second parameter to run app level ping
// this is mainly used for browser to track pings at client level
// as they do not expose on ping listener 
// look for browser client side implementation at the bottom
// `Handle App Level Ping In Browser (example)`
wsServer.startAutoPing(10000, true);

To stop server use close function:

wsServer.close(() => {
  // triggered after server has been stopped
})

handleUpgrade is function which is commonly used together with noServer (same as ws module)

const wss = new WebSocket.Server({ noServer: true });
const server = http.createServer();

wss.on('connection', (ws, req) => { })

server.on('upgrade', (request, socket, head) => {
  wss.handleUpgrade(request, socket, head, (ws) => {
      wss.emit('connection', ws, request);
  });
});

For more information check typings (*.d.ts) files in dist folder

Secure WebSocket

You can use wss:// with cws by providing https server to cws and setting secureProtocol on https options:

const { readFileSync } = require('fs');
const { createServer }  = require('https');
const { WebSocket, secureProtocol  } = require('@clusterws/cws');

const options = {
  key: readFileSync(/** path to key */),
  cert: readFileSync(/** path to certificate */),
  secureProtocol
  // ...other Node HTTPS options
};

const server = createServer(options);
const wsServer = new WebSocket.Server({ server });
// your secure ws is ready (do your usual things)

server.listen(port, () => {
  console.log('Server is running');
})

For more detail example check examples folder

Handle App Level Ping In Browser (example)

Handling custom App level ping, pong from the client side which does not have onping and onpong listeners available such as browsers.

Note if all your clients have onping and onpong listeners do not send appLevelPing ping from the server. If you enable appLevelPing you will need to implement similar handler for every client library which connects to the server.

const PING = 57;
const PONG = new Uint8Array(['A'.charCodeAt()]);

socket.binaryType = 'arraybuffer';

socket.onmessage = function (message) {
    // note actually sent message in
    // browser default WebSocket is under `message.data`

    // check if message is not string 
    if (typeof message.data !== 'string') {
        // transform it to Uint8Array
        let buffer = new Uint8Array(message.data);

        // Check if it is actually ping from the server
        if (buffer.length === 1 && buffer[0] === PING) {
            // this is definitely `ping` event you can call custom on ping handler 
            // also must send back immediately pong to the server 
            // otherwise server will disconnect this client
            return socket.send(PONG);
        }
    }

    // process with your logic
}

版本与发布记录

@clusterws/cws 共发布 33 个版本,首次发布于 2018/11/26;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.0.0latest2020/07/046 年前
2.0.02020/05/096 年前
1.6.02020/04/106 年前
1.5.02020/03/066 年前
1.4.02020/02/296 年前
1.3.12020/02/276 年前

关于 @clusterws/cws 的常见问题

@clusterws/cws 是什么?

cWS - fast C++ WebSocket implementation for Node.js

如何安装 @clusterws/cws?

在项目目录运行 npm install @clusterws/cws,或使用 pnpm add / yarn add / bun add。

@clusterws/cws 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@clusterws/cws 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@clusterws/cws 可以商用吗?

@clusterws/cws 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@clusterws/cws 的下载量有多少?

根据 npm 官方下载统计,@clusterws/cws 在 2026/10/10 – 2026/11/08 这 30 天内被下载 2,172 次,日均约 72 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@clusterws/cws 还在维护吗?

最新版本 3.0.0 发布于 2020/07/04(6 年前);至今共发布 33 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/11/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。