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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@alipay-inc/mpaas-mgs-sdk-websocket

v1.0.0-beta.5

Published

A WebSocket SDK for mPaaS MGS with connection management, reconnection, and event handling

Downloads

42

Readme

mPaaS MGS WebSocket SDK

一个功能完整的 WebSocket 客户端 SDK,专为 mPaaS MGS 平台设计,提供连接管理、自动重连、心跳检测、消息队列等企业级功能。

项目特性

  • 🔌 自动连接管理 - 智能连接状态管理和错误处理
  • 🔄 自动重连机制 - 可配置的重连策略,确保连接稳定性
  • 💓 心跳检测 - 定时心跳保持连接活跃
  • 📦 消息队列 - 连接断开时自动缓存消息,连接恢复后重发
  • 📊 连接统计 - 详细的连接和消息统计信息
  • 🎯 事件驱动 - 完整的事件系统,支持各种连接状态监听
  • 🛠️ TypeScript 支持 - 完整的类型定义,提供优秀的开发体验
  • 📝 日志系统 - 可配置的日志级别,便于调试和监控

兼容环境

  • 浏览器: 支持现代浏览器(Chrome 58+, Firefox 55+, Safari 11+, Edge 79+)
  • Node.js: 支持 Node.js 14+ 环境(需要 WebSocket polyfill)
  • TypeScript: 支持 TypeScript 4.0+

安装方法

npm install mpaas-mgs-sdk-websocket

或使用 yarn:

yarn add mpaas-mgs-sdk-websocket

快速开始

基本使用

import { WebSocketClient, WebSocketEventType } from 'mpaas-mgs-sdk-websocket';

// 创建客户端实例
const client = new WebSocketClient({
  url: 'wss://your-websocket-server.com',
  autoReconnect: true,
  heartbeatInterval: 30000
});

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

// 监听消息事件
client.on(WebSocketEventType.MESSAGE, (event) => {
  console.log('收到消息:', event.data);
});

// 连接服务器
await client.connect();

// 发送消息
await client.send('Hello WebSocket!');

高级配置

import { WebSocketClient, LogLevel, Logger } from 'mpaas-mgs-sdk-websocket';

// 设置日志级别
Logger.getInstance().setLevel(LogLevel.DEBUG);

// 创建高级配置的客户端
const client = new WebSocketClient({
  url: 'wss://your-websocket-server.com',
  protocols: ['chat', 'notification'],
  timeout: 10000,
  autoReconnect: true,
  reconnectInterval: 5000,
  maxReconnectAttempts: 10,
  heartbeatInterval: 30000,
  heartbeatMessage: JSON.stringify({ type: 'ping' }),
  headers: {
    'Authorization': 'Bearer your-token',
    'X-Client-Version': '1.0.0'
  }
});

API 文档

WebSocketClient

主要的 WebSocket 客户端类。

构造函数

new WebSocketClient(config: WebSocketConfig)

配置选项 (WebSocketConfig)

| 参数 | 类型 | 默认值 | 说明 | |------|------|--------|------| | url | string | - | WebSocket 服务器 URL(必填) | | protocols | string \| string[] | [] | 连接协议 | | timeout | number | 10000 | 连接超时时间(毫秒) | | autoReconnect | boolean | true | 是否自动重连 | | reconnectInterval | number | 3000 | 重连间隔时间(毫秒) | | maxReconnectAttempts | number | 5 | 最大重连次数 | | heartbeatInterval | number | 30000 | 心跳间隔时间(毫秒) | | heartbeatMessage | string | 'ping' | 心跳消息内容 | | headers | Record<string, string> | {} | 自定义请求头 |

主要方法

connect(): Promise

连接到 WebSocket 服务器。

try {
  await client.connect();
  console.log('连接成功');
} catch (error) {
  console.error('连接失败:', error);
}
disconnect(code?: number, reason?: string): void

断开 WebSocket 连接。

client.disconnect(1000, '正常关闭');
send(data: string | ArrayBuffer | Blob, options?: SendOptions): Promise

发送消息到服务器。

// 发送文本消息
await client.send('Hello World!');

// 发送 JSON 消息
await client.send(JSON.stringify({ type: 'message', content: 'Hello' }));

// 带选项发送
await client.send('message', {
  waitForConnection: true,
  timeout: 5000
});
isConnected(): boolean

检查是否已连接。

if (client.isConnected()) {
  await client.send('message');
}
getState(): WebSocketState

获取当前连接状态。

import { WebSocketState } from 'mpaas-mgs-sdk-websocket';

const state = client.getState();
console.log('当前状态:', state === WebSocketState.OPEN ? '已连接' : '未连接');
getStats(): WebSocketStats

获取连接统计信息。

const stats = client.getStats();
console.log('统计信息:', {
  state: stats.state,
  connectedAt: stats.connectedAt,
  sentMessages: stats.sentMessageCount,
  receivedMessages: stats.receivedMessageCount,
  reconnectCount: stats.reconnectCount
});
updateConfig(config: Partial): void

动态更新配置。

client.updateConfig({
  heartbeatInterval: 15000,
  maxReconnectAttempts: 10
});
destroy(): void

销毁客户端实例,清理所有资源。

client.destroy();

事件系统

SDK 基于事件驱动架构,支持以下事件:

WebSocketEventType

| 事件 | 说明 | 事件数据 | |------|------|----------| | OPEN | 连接建立 | Event | | MESSAGE | 收到消息 | MessageEvent | | ERROR | 连接错误 | Event | | CLOSE | 连接关闭 | CloseEvent | | RECONNECTING | 正在重连 | { attempt: number } | | RECONNECTED | 重连成功 | Event | | RECONNECT_FAILED | 重连失败 | { maxAttempts: number } |

事件监听示例

import { WebSocketEventType } from 'mpaas-mgs-sdk-websocket';

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

// 监听消息事件
client.on(WebSocketEventType.MESSAGE, (event) => {
  console.log('收到消息:', event.data);
});

// 监听重连事件
client.on(WebSocketEventType.RECONNECTING, (data) => {
  console.log(`正在进行第 ${data.attempt} 次重连...`);
});

// 一次性监听器
client.once(WebSocketEventType.OPEN, () => {
  console.log('首次连接成功');
});

// 移除监听器
const messageHandler = (event) => console.log(event.data);
client.on(WebSocketEventType.MESSAGE, messageHandler);
client.off(WebSocketEventType.MESSAGE, messageHandler);

日志系统

SDK 内置了完整的日志系统:

import { Logger, LogLevel } from 'mpaas-mgs-sdk-websocket';

const logger = Logger.getInstance();

// 设置日志级别
logger.setLevel(LogLevel.DEBUG); // DEBUG, INFO, WARN, ERROR, NONE

// 设置日志前缀
logger.setPrefix('[MyApp]');

// 日志输出
logger.debug('调试信息');
logger.info('一般信息');
logger.warn('警告信息');
logger.error('错误信息');

使用示例

聊天应用示例

import { WebSocketClient, WebSocketEventType } from 'mpaas-mgs-sdk-websocket';

interface ChatMessage {
  type: 'message' | 'join' | 'leave';
  user: string;
  content: string;
  timestamp: number;
}

const chatClient = new WebSocketClient({
  url: 'wss://chat.example.com',
  autoReconnect: true,
  heartbeatInterval: 30000
});

// 发送聊天消息
async function sendChatMessage(user: string, content: string) {
  const message: ChatMessage = {
    type: 'message',
    user,
    content,
    timestamp: Date.now()
  };
  
  await chatClient.send(JSON.stringify(message));
}

// 处理接收的消息
chatClient.on(WebSocketEventType.MESSAGE, (event) => {
  try {
    const message: ChatMessage = JSON.parse(event.data);
    console.log(`[${message.user}]: ${message.content}`);
  } catch (error) {
    console.error('消息解析失败:', error);
  }
});

// 连接并加入聊天
await chatClient.connect();
await sendChatMessage('Alice', 'Hello everyone!');

实时数据监控示例

import { WebSocketClient, WebSocketEventType } from 'mpaas-mgs-sdk-websocket';

const monitorClient = new WebSocketClient({
  url: 'wss://monitor.example.com',
  autoReconnect: true,
  reconnectInterval: 2000,
  maxReconnectAttempts: -1, // 无限重连
  heartbeatInterval: 10000
});

// 订阅数据流
async function subscribe(channels: string[]) {
  const subscribeMessage = {
    action: 'subscribe',
    channels
  };
  
  await monitorClient.send(JSON.stringify(subscribeMessage));
}

// 处理实时数据
monitorClient.on(WebSocketEventType.MESSAGE, (event) => {
  const data = JSON.parse(event.data);
  
  switch (data.type) {
    case 'metrics':
      updateMetricsDashboard(data.payload);
      break;
    case 'alert':
      showAlert(data.payload);
      break;
    case 'heartbeat':
      console.log('服务器心跳正常');
      break;
  }
});

// 连接并订阅
await monitorClient.connect();
await subscribe(['cpu', 'memory', 'network']);

错误处理

SDK 提供了完善的错误处理机制:

// 连接错误处理
client.on(WebSocketEventType.ERROR, (event) => {
  console.error('WebSocket 错误:', event);
});

// 连接关闭处理
client.on(WebSocketEventType.CLOSE, (event) => {
  console.log('连接关闭:', {
    code: event.code,
    reason: event.reason,
    wasClean: event.wasClean
  });
});

// 重连失败处理
client.on(WebSocketEventType.RECONNECT_FAILED, (data) => {
  console.error(`重连失败,已尝试 ${data.maxAttempts} 次`);
  // 可以在这里实现自定义的错误恢复逻辑
});

// 发送消息错误处理
try {
  await client.send('message');
} catch (error) {
  console.error('发送消息失败:', error);
}

最佳实践

1. 连接管理

// 推荐:使用 try-catch 处理连接
try {
  await client.connect();
} catch (error) {
  console.error('初始连接失败,将依赖自动重连机制');
}

// 推荐:在应用退出时优雅关闭
window.addEventListener('beforeunload', () => {
  client.disconnect(1000, '页面关闭');
});

2. 消息处理

// 推荐:使用消息队列确保消息不丢失
await client.send('important message', {
  waitForConnection: true,
  timeout: 10000
});

// 推荐:结构化消息格式
interface AppMessage {
  id: string;
  type: string;
  payload: any;
  timestamp: number;
}

async function sendAppMessage(type: string, payload: any) {
  const message: AppMessage = {
    id: generateId(),
    type,
    payload,
    timestamp: Date.now()
  };
  
  await client.send(JSON.stringify(message));
}

3. 错误处理和监控

// 推荐:实现完整的事件监听
client.on(WebSocketEventType.OPEN, () => {
  console.log('✅ 连接成功');
  // 发送认证消息、订阅数据等
});

client.on(WebSocketEventType.RECONNECTING, (data) => {
  console.log(`🔄 重连中... (${data.attempt}/${maxAttempts})`);
  // 显示重连状态给用户
});

client.on(WebSocketEventType.RECONNECTED, () => {
  console.log('✅ 重连成功');
  // 重新订阅数据、同步状态等
});

开发和构建

环境要求

  • Node.js 14+
  • TypeScript 4.0+

安装依赖

npm install

开发模式

npm run dev

构建项目

npm run build

运行测试

npm test

代码检查

npm run lint

主要项目负责人

  • @mPaaS Team

参与贡献

欢迎提交 Issue 和 Pull Request 来改进这个项目。

  1. Fork 本仓库
  2. 创建你的特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交你的修改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 开启一个 Pull Request

许可证

本项目采用 MIT 许可证。详情请参阅 LEGAL.md 文件。

更新日志

v1.0.0

  • 🎉 首次发布
  • ✨ 完整的 WebSocket 连接管理
  • 🔄 自动重连机制
  • 💓 心跳检测功能
  • 📦 消息队列支持
  • 📊 连接统计功能
  • 🎯 事件驱动架构
  • 🛠️ TypeScript 支持
  • 📝 完整的日志系统