npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

cy-plugin-websocket

v2.0.5

Published

封装 websocket 插件

Readme

cy-plugin-websocket

一个功能完整的 WebSocket 客户端封装库,支持心跳、自动重连、事件监听等特性。

✨ 特性

  • 🔄 自动重连 - 支持指数退避重连策略
  • 💓 心跳机制 - 可配置的心跳检测
  • 📦 消息队列 - 连接断开时自动缓存消息
  • 🎯 事件系统 - 基于 Emittery 的事件监听
  • 🛡️ 类型安全 - 完整的 TypeScript 支持
  • 🔧 高度可配置 - 丰富的配置选项

📦 安装

npm install cy-plugin-websocket

依赖要求

本项目依赖 emittery 作为事件系统,请确保已安装:

npm install [email protected] --save

🚀 快速开始

基础用法

注意: 使用事件监听时,请使用 enumSocketEvent 枚举而不是字符串,这样可以获得更好的类型安全性和 IDE 支持。

import { SocketClient, enumSocketEvent } from 'cy-plugin-websocket';

// 创建 WebSocket 连接
const socket = new SocketClient('wss://example.com/ws');

// 建立连接
socket.connect();

// 监听事件
socket.on(enumSocketEvent.OPEN, () => {
  console.log('连接已建立');
});

socket.on(enumSocketEvent.MESSAGE, (data) => {
  console.log('收到消息:', data);
});

socket.on(enumSocketEvent.CLOSE, (code, reason) => {
  console.log('连接已关闭:', code, reason);
});

socket.on(enumSocketEvent.ERROR, (error) => {
  console.log('连接错误:', error);
});

// 发送消息
socket.send({ type: 'chat', message: 'Hello World' });

// 移除事件监听器
const messageHandler = (data) => {
  console.log('收到消息:', data);
};

socket.on(enumSocketEvent.MESSAGE, messageHandler);

// 稍后移除监听器
socket.off(enumSocketEvent.MESSAGE, messageHandler);

高级配置

import SocketClient, { enumSocketEvent } from 'cy-plugin-websocket';

const socket = new SocketClient('wss://example.com/ws', {
  // 开启调试模式
  debug: true,

  // 开启自动重连
  connectResend: true,

  // 心跳配置
  heartOption: {
    message: { type: 'ping' },
    interval: 30000 // 30秒心跳
  },

  // 重连配置
  reconnectOption: {
    maxCount: 5, // 最大重连次数
    interval: 2000, // 重连间隔
    maxInterval: 10000 // 最大重连间隔
  },

  // 自定义消息处理
  handleMessage: (data) => {
    console.log('处理消息:', data);
    return data;
  }
});

socket.connect();

// 使用 on 方法监听事件
socket.on(enumSocketEvent.OPEN, () => {
  console.log('连接已建立');
});

socket.on(enumSocketEvent.MESSAGE, (data) => {
  console.log('收到消息:', data);
});

// 使用 off 方法移除监听器
const errorHandler = (error) => {
  console.log('连接错误:', error);
};

socket.on(enumSocketEvent.ERROR, errorHandler);

// 稍后移除错误监听器
socket.off(enumSocketEvent.ERROR, errorHandler);

📚 API 文档

构造函数

new SocketClient(url: string, options?: ISocketOption)

参数

  • url - WebSocket 服务器地址
  • options - 配置选项(可选)

配置选项 (ISocketOption)

| 参数 | 类型 | 默认值 | 描述 | | ----------------- | --------------------------------- | ------- | ---------------- | | debug | boolean | false | 是否开启调试模式 | | connectResend | boolean | false | 是否开启自动重连 | | heartOption | ISocketHeartOption | - | 心跳配置 | | reconnectOption | ISocketReconnectOption | - | 重连配置 | | handleMessage | (data: MessageEvent) => unknown | - | 消息处理函数 |

心跳配置 (ISocketHeartOption)

| 参数 | 类型 | 默认值 | 描述 | | ---------- | -------- | ------------------ | ---------------- | | message | any | { beat: 'beat' } | 心跳消息内容 | | interval | number | 3000 | 心跳间隔(毫秒) |

重连配置 (ISocketReconnectOption)

| 参数 | 类型 | 默认值 | 描述 | | ------------- | -------- | ---------- | -------------------- | | maxCount | number | Infinity | 最大重连次数 | | interval | number | 5000 | 重连间隔(毫秒) | | maxInterval | number | 60000 | 最大重连间隔(毫秒) |

方法

connect()

建立 WebSocket 连接

socket.connect();

send(message: unknown)

发送消息

// 发送对象
socket.send({ type: 'chat', message: 'Hello' });

// 发送字符串
socket.send('Hello World');

close()

主动关闭连接

socket.close();

destroy()

销毁连接并清理资源

socket.destroy();

on(event, listener)

添加事件监听器

import { enumSocketEvent } from 'cy-plugin-websocket';

// 监听连接建立事件
socket.on(enumSocketEvent.OPEN, () => {
  console.log('连接已建立');
});

// 监听消息事件
const messageHandler = (data) => {
  console.log('收到消息:', data);
};
socket.on(enumSocketEvent.MESSAGE, messageHandler);

// 监听连接关闭事件
socket.on(enumSocketEvent.CLOSE, (code, reason) => {
  console.log('连接已关闭:', code, reason);
});

// 监听错误事件
socket.on(enumSocketEvent.ERROR, (error) => {
  console.log('连接错误:', error);
});

off(event, listener)

移除事件监听器

// 移除特定的消息监听器
socket.off(enumSocketEvent.MESSAGE, messageHandler);

// 移除所有错误监听器
socket.off(enumSocketEvent.ERROR);

once(event, listener)

添加一次性事件监听器

// 只监听一次连接建立事件
socket.once(enumSocketEvent.OPEN, () => {
  console.log('连接已建立,只执行一次');
});

// 只监听一次消息事件
socket.once(enumSocketEvent.MESSAGE, (data) => {
  console.log('收到第一条消息:', data);
});

offAll()

移除所有事件监听器

// 移除所有事件的所有监听器
socket.offAll();

// 通常在组件销毁时使用
socket.destroy();
socket.offAll();

事件

| 事件 | 参数 | 描述 | | --------- | ------------ | -------- | | open | Event | 连接建立 | | message | unknown | 收到消息 | | close | CloseEvent | 连接关闭 | | error | Event | 连接错误 |

属性

state

获取当前连接状态

const state = socket.state;
// 0: CONNECTING
// 1: OPEN
// 2: CLOSING
// 3: CLOSED