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

@cf-platform/cim

v1.0.2

Published

消息队列库

Readme

@cf-platform/cim

一个基于WebSocket的即时通讯客户端库,支持自动重连、心跳检测和消息收发功能。

安装

npm install @cf-platform/cim

快速开始

import { CIM } from '@cf-platform/cim';

// 创建CIM实例
const cim = new CIM({
  url: 'wss://127.0.0.1:8080',
  restartInterval: 3000,
  loginParams: {
    uid: 'user123',
    appVersion: '1.0.0',
    deviceId: 'device-001'
  },
  customEvents: {
    onLoginSuccess: (reply) => console.log('登录成功:', reply),
    onMessage: (message) => console.log('收到消息:', message),
    onSocketError: () => console.error('连接错误')
  }
});

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

// 发送消息
cim.sendMessage({
  key: 'send_message',
  content: 'Hello World',
  receiver: 'user456'
});

// 关闭连接(页面卸载时调用)
// cim.close();

API文档

一、初始化

1. 初始化参数 CIMOptions

| 参数名 | 描述 | 类型 | 默认值 | 必填 | |-----------------|------------------------|----------------|----------|----| | url | WebSocket服务器地址 | string | - | ✓ | | restartInterval | 自动重连间隔(毫秒) | number | 3000 | | | loginParams | 登录认证参数 | LoginParams | - | ✓ | | customEvents | 自定义事件回调函数 | CustomEvents | null | |

2. 登录参数 LoginParams

| 字段名 | 描述 | 类型 | 默认值 | 必填 | |-------------|------------------------|----------|-------------------------------|----| | uid | 用户唯一标识符 | string | - | ✓ | | channel | 客户端通道类型 | string | web | | | appVersion | 应用版本号 | string | - | ✓ | | osVersion | 操作系统版本号 | string | 自动检测浏览器版本 | | | packageName | 应用包名 | string | com.farsunset.cim | | | language | 系统语言设置 | string | 自动检测浏览器语言 | | | deviceId | 设备唯一标识符 | string | - | ✓ | | deviceName | 设备名称 | string | 自动检测浏览器名称 | | | custom | 自定义扩展参数 | any | - | |

3. 自定义事件 CustomEvents

| 事件名 | 描述 | 参数类型 | 触发时机 | |------------------------|------------------------|--------------------------|---------------------------| | onSocketOpen | WebSocket连接成功 | () => void | 连接建立成功 | | onSocketConnect | 开始连接WebSocket | (url: string) => void | 开始建立连接 | | onSocketClose | WebSocket连接关闭 | () => void | 连接关闭 | | onSocketError | WebSocket连接错误 | () => void | 连接发生错误 | | onSendPong | 发送心跳包 | () => void | 向服务器发送心跳包 | | onMessage | 收到服务器消息 | (message: any) => void | 收到普通消息 | | onReply | 收到服务器回复 | (reply: any) => void | 收到服务器回复消息 | | onLoginSuccess | 登录认证成功 | (reply: any) => void | 客户端绑定认证成功 | | onLoginDisconnected | 登录连接断开 | (reply: any) => void | 客户端关闭连接 | | onAuthenticationFailed | 鉴权失败 | (reply: any) => void | 握手认证失败 |

二、核心方法

1. 连接管理

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

// 重新连接
cim.reconnect();

// 关闭连接(手动关闭后不会自动重连)
cim.close();

// 检查连接状态
const isConnected = cim.isConnected();
const isConnecting = cim.isConnecting();
const connectionState = cim.getConnectionState();

2. 消息收发

// 发送消息
cim.sendMessage({
  key: 'send_message',           // 消息类型
  content: 'Hello World',        // 消息内容
  receiver: 'user456',           // 接收者ID
  timestamp: Date.now()          // 时间戳
});

// 发送广播消息
cim.sendMessage({
  key: 'broadcast_message',
  content: '系统通知',
  target: 'all_users'
});

// 关闭客户端连接
cim.sendMessage({
  key: 'client_closed'
});

3. 消息类型说明

| 消息类型Key | 描述 | 用途 | |---------------------|--------------|------------------------| | client_bind | 客户端绑定 | 登录认证 | | client_closed | 客户端关闭 | 主动断开连接 | | client_handshake | 客户端握手 | 握手认证 | | send_message | 发送消息 | 点对点消息 | | broadcast_message | 广播消息 | 群发消息 |

三、完整示例

1. 基础使用

import { CIM } from '@cf-platform/cim';

// 创建CIM实例
const cim = new CIM({
  url: 'wss://your-server.com:8080',
  restartInterval: 5000, // 5秒重连间隔
  loginParams: {
    uid: 'user123',
    appVersion: '1.0.0',
    deviceId: 'browser-user-001'
  },
  customEvents: {
    onSocketOpen: () => console.log('连接成功'),
    onSocketConnect: (url) => console.log('开始连接:', url),
    onSocketClose: () => console.log('连接关闭'),
    onSocketError: () => console.error('连接错误'),
    onLoginSuccess: (reply) => console.log('登录成功:', reply),
    onMessage: (message) => {
      console.log('收到消息:', message);
      // 处理消息逻辑
    },
    onAuthenticationFailed: (reply) => {
      console.error('认证失败:', reply);
      // 处理认证失败逻辑
    }
  }
});

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

// 页面卸载时关闭连接
window.addEventListener('beforeunload', () => {
  cim.close();
});

2. React组件中使用

import React, { useEffect, useState } from 'react';
import { CIM } from '@cf-platform/cim';

const ChatComponent: React.FC = () => {
  const [cim, setCim] = useState<CIM | null>(null);
  const [messages, setMessages] = useState<any[]>([]);
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    const cimInstance = new CIM({
      url: 'wss://your-server.com:8080',
      loginParams: {
        uid: 'user123',
        appVersion: '1.0.0',
        deviceId: 'react-app-001'
      },
      customEvents: {
        onLoginSuccess: () => setIsConnected(true),
        onSocketClose: () => setIsConnected(false),
        onMessage: (message) => {
          setMessages(prev => [...prev, message]);
        }
      }
    });

    cimInstance.connect();
    setCim(cimInstance);

    return () => {
      cimInstance.close();
    };
  }, []);

  const sendMessage = (content: string) => {
    if (cim && isConnected) {
      cim.sendMessage({
        key: 'send_message',
        content,
        receiver: 'target-user'
      });
    }
  };

  return (
    <div>
      <div>连接状态: {isConnected ? '已连接' : '未连接'}</div>
      <div>
        {messages.map((msg, index) => (
          <div key={index}>{msg.content}</div>
        ))}
      </div>
      <button onClick={() => sendMessage('Hello')}>发送消息</button>
    </div>
  );
};

四、API参考

CIM类

export class CIM {
  /**
   * 构造函数
   * @param options - CIM配置选项
   */
  constructor(options: CIMOptions);
  
  /**
   * 初始化或重新配置CIM客户端
   * @param options - 新的配置选项
   */
  initialize(options: CIMOptions): void;
  
  /**
   * 建立WebSocket连接
   * @throws {Error} 连接地址为空时抛出错误
   */
  connect(): void;
  
  /**
   * 重新连接WebSocket
   */
  reconnect(): void;
  
  /**
   * 关闭WebSocket连接(手动关闭后不会自动重连)
   */
  close(): void;
  
  /**
   * 发送心跳包到服务器
   */
  sendPong(): void;
  
  /**
   * 发送消息到服务器
   * @param data - 消息数据对象
   */
  sendMessage(data: CIMMessage): void;
  
  /**
   * 获取WebSocket连接状态
   * @returns WebSocket连接状态码
   */
  getConnectionState(): number;
  
  /**
   * 检查是否已连接
   * @returns 是否处于已连接状态
   */
  isConnected(): boolean;
  
  /**
   * 检查是否正在连接中
   * @returns 是否处于连接中状态
   */
  isConnecting(): boolean;
}

五、注意事项

  1. 连接管理: 在页面卸载前务必调用 close() 方法关闭连接
  2. 自动重连: 默认启用3000ms自动重连,设置为0可禁用
  3. 心跳机制: 库会自动处理心跳包,无需手动调用 sendPong()
  4. 错误处理: 通过 customEvents 注册错误回调进行错误处理
  5. 浏览器兼容: 支持现代浏览器,需要WebSocket和TypedArray支持

六、故障排除

  • 连接失败: 检查服务器地址是否正确,网络是否通畅
  • 认证失败: 确认登录参数(uid、appVersion、deviceId)是否正确
  • 消息发送失败: 检查连接状态,确保连接建立后再发送消息
  • 自动重连频繁: 适当调整 restartInterval 参数

许可证

ISC License