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

comind-im-client-sdk

v1.0.16

Published

comind-im-client-sdk 版本升级

Readme

IM Client SDK

即时通讯客户端SDK,提供连接、鉴权、消息发送、群组管理等功能。

目录

安装

通过NPM安装

npm install comind-im-client-sdk --save

直接引入

<!-- 先引入Socket.IO客户端库 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/socket.io.js"></script>
<!-- 引入IM SDK -->
<script src="path/to/comind-im-client-sdk.js"></script>

初始化流程

IM SDK的标准初始化流程包括三个关键步骤:创建实例、获取令牌和连接服务器。

完整初始化示例

// 1. 创建SDK实例
const imClient = new ImClient({
  serverUrl: 'http://your-socket-server:9998',  // Socket.IO服务器地址
  apiServer: 'http://your-api-server:8890',     // API服务器地址(重要:必须设置)
  reconnection: true,                           // 是否自动重连
  reconnectionAttempts: 5,                      // 重连尝试次数
  reconnectionDelay: 3000,                      // 重连延迟(毫秒)
  timeout: 30000,                               // 连接超时时间(毫秒)
  pingInterval: 25000,                          // 心跳间隔(毫秒)
  pingTimeout: 60000                            // 心跳超时(毫秒)
});

// 2. 注册事件回调
imClient.on('connect', () => {
  console.log('连接成功');
});

imClient.on('disconnect', (reason) => {
  console.log('连接断开', reason);
});

imClient.on('error', (error) => {
  console.error('发生错误', error);
});

imClient.on('status', (status) => {
  console.log('连接状态', status);
});

imClient.on('imchat', (message) => {
  console.log('收到消息', message);
});

// 3. 获取认证令牌
const token = await imClient.getToken({
  apiServer: 'http://your-api-server:8890',  // API服务器地址
  appId: 'your-app-id',                      // 应用ID
  appSecret: 'your-app-secret',              // 应用密钥
  userId: 'user123',                         // 用户ID
  userName: 'Alice'                          // 用户名
});

// 4. 连接到服务器
await imClient.connect({
  serverUrl: 'http://your-socket-server:9998'
});

console.log('初始化完成');

用户管理

注册/更新用户

注册新用户或更新现有用户信息:

// 注册或更新用户
const userInfo = {
  apiServer: 'http://your-api-server:8890',  // API服务器地址(必填参数)
  appId: "app123456",                        // 应用ID(必填参数)
  appSecret: "sec123456",                    // 应用密钥(必填参数)
  userId: "user123",                         // 用户ID(必填参数)
  userName: "张三",                          // 用户名称
  userImg: "https://example.com/avatar.jpg", // 用户头像URL
  companyName: "某某科技有限公司",           // 公司名称
  imRole: "user",                            // IM角色,可选值:user,admin,guest
  valid: true                                // 用户有效性
};

// 重要提示:apiServer 是必填参数,不能为空
// 正确示例:apiServer: "http://192.168.11.92:8890"

imClient.registerUser(userInfo)
  .then(response => {
    console.log('用户注册/更新成功:', response);
  })
  .catch(error => {
    console.error('用户注册/更新失败:', error);
  });

获取用户信息

const userInfo = await imClient.getUserInfo({
  apiServer: 'http://your-api-server:8890',  // API服务器地址
  userId: 'user456'                          // 用户ID
});

console.log('用户信息', userInfo);

消息发送接收

发送私聊消息

// 发送私聊消息
const result = await imClient.sendPrivateMessage({
  content: 'Hello!',        // 消息内容
  recipientId: 'user456'    // 接收者ID
});

console.log('消息发送成功', result.messageId);

发送群聊消息

// 发送群聊消息
const result = await imClient.sendGroupMessage({
  content: 'Hello group!',  // 消息内容
  groupId: 'group123'       // 群组ID
});

console.log('群聊消息发送成功', result.messageId);

接收消息

通过事件监听接收消息:

// 监听所有聊天消息(私聊和群聊)
imClient.on('imchat', (message) => {
  // 判断消息类型
  if (message.chatType === 0) {
    console.log('收到私聊消息:', message);
  } else if (message.chatType === 1) {
    console.log('收到群聊消息:', message);
  }
  
  // 消息内容格式示例:
  // {
  //   messageId: 'xxx-xxx-xxx',
  //   from: 'user123',
  //   fromName: 'Alice',
  //   to: 'user456' 或 'group789',
  //   content: '消息内容',
  //   chatType: 0或1,  // 0=私聊, 1=群聊
  //   timestamp: 1631234567890,
  //   msgType: 0,  // 0=文本消息
  //   data: {...}  // 额外数据
  // }
});

// 监听消息回执
imClient.on('receipt', (receipt) => {
  console.log('消息回执:', receipt);
  // receipt = { messageId: 'xxx', status: 2, timestamp: 1631234567890 }
});

发送已读回执

// 发送已读回执
imClient.sendReadReceipt('message-123', 'sender-456');

群组管理

创建群组

const groupInfo = await imClient.createGroup({
  apiServer: 'http://your-api-server:8890',  // API服务器地址
  name: 'My Group',                          // 群组名称
  description: 'This is my group',           // 群组描述
  userIdList: ['user456', 'user789']         // 成员列表
});

console.log('群组创建成功', groupInfo.id);

获取群组列表

const groups = await imClient.getGroupList({
  apiServer: 'http://your-api-server:8890'   // API服务器地址
});

console.log('群组列表', groups);

获取群组信息

const groupInfo = await imClient.getGroupInfo({
  apiServer: 'http://your-api-server:8890',  // API服务器地址
  groupId: 'group123'                        // 群组ID
});

console.log('群组信息', groupInfo);

获取群组成员

const members = await imClient.getGroupMembers({
  apiServer: 'http://your-api-server:8890',  // API服务器地址
  groupId: 'group123'                        // 群组ID
});

console.log('群组成员', members);

获取群组历史消息

const historyMessages = await imClient.getGroupHistoryMessages({
  apiServer: 'http://your-api-server:8890',  // API服务器地址
  groupId: 'group123',                       // 群组ID
  limitSize: 20,                             // 获取消息数量
  msgSeqId: 0,                               // 开始的消息序列ID
  syncType: 'BACK',                          // 同步方向
  detailType: 0                              // 详情类型
});

console.log('群组历史消息', historyMessages);

事件机制

SDK提供了丰富的事件监听机制,可以实时响应各种状态变化和消息。

注册事件监听

// 添加事件监听器
imClient.on('eventName', callback);

// 示例:监听连接状态
imClient.on('status', (status) => {
  console.log('连接状态变化:', status);
});

移除事件监听

// 移除特定事件的特定回调函数
imClient.off('eventName', callback);

可用事件列表

| 事件名 | 参数 | 描述 | |--------|------|------| | connect | 无 | 连接服务器成功 | | disconnect | reason: String | 连接断开 | | message | message: Object | 收到消息(兼容旧版本) | | error | error: String | 发生错误 | | reconnect | attemptNumber: Number | 重连成功 | | status | status: String | 连接状态更新 | | imchat | message: Object | 收到聊天消息(包括私聊和群聊) | | receipt | receipt: Object | 收到消息回执 |

连接管理

断开连接

// 主动断开连接
imClient.disconnect();

心跳检测

// 发送手动心跳
imClient.sendHeartbeat();

// 获取心跳状态
const status = imClient.getHeartbeatStatus(); // 'active' 或 'inactive'

API参考

构造函数选项

| 选项 | 类型 | 默认值 | 描述 | |------|------|--------|------| | serverUrl | String | - | Socket.IO服务器地址 | | apiServer | String | - | API服务器地址 | | reconnection | Boolean | true | 是否自动重连 | | reconnectionAttempts | Number | 5 | 重连尝试次数 | | reconnectionDelay | Number | 3000 | 重连延迟(毫秒) | | timeout | Number | 30000 | 连接超时时间(毫秒) | | pingInterval | Number | 25000 | 心跳间隔(毫秒) | | pingTimeout | Number | 60000 | 心跳超时(毫秒) |

核心方法

初始化与连接

| 方法名 | 参数 | 返回值 | 描述 | |--------|------|--------|------| | getToken | { apiServer, appId, appSecret, userId, userName } | Promise<String> | 获取认证令牌 | | connect | { serverUrl } | Promise<Boolean> | 连接到服务器 | | disconnect | 无 | void | 断开连接 | | sendHeartbeat | 无 | Boolean | 发送手动心跳 | | getHeartbeatStatus | 无 | String | 获取心跳状态 |

用户管理

| 方法名 | 参数 | 返回值 | 描述 | |--------|------|--------|------| | getUserInfo | { apiServer, userId } | Promise<Object> | 获取用户信息 | | registerUser | { apiServer, appId, appSecret, userId, userName, userImg, companyName, imRole, valid } | Promise<Object> | 注册/更新用户 |

消息管理

| 方法名 | 参数 | 返回值 | 描述 | |--------|------|--------|------| | sendPrivateMessage | { content, recipientId } | Promise<Object> | 发送私聊消息 | | sendGroupMessage | { content, groupId } | Promise<Object> | 发送群聊消息 | | sendReadReceipt | messageId: String, toUserId: String | Boolean | 发送已读回执 |

群组管理

| 方法名 | 参数 | 返回值 | 描述 | |--------|------|--------|------| | createGroup | { apiServer, name, description, userIdList } | Promise<Object> | 创建群组 | | getGroupList | { apiServer } | Promise<Array> | 获取群组列表 | | getGroupMembers | { apiServer, groupId } | Promise<Array> | 获取群组成员 | | getGroupInfo | { apiServer, groupId } | Promise<Object> | 获取群组信息 | | getGroupHistoryMessages | { apiServer, groupId, limitSize, msgSeqId, syncType, detailType } | Promise<Array> | 获取群组历史消息 |

事件监听

| 方法名 | 参数 | 返回值 | 描述 | |--------|------|--------|------| | on | event: String, callback: Function | ImClient | 注册事件监听 | | off | event: String, callback: Function | ImClient | 移除事件监听 |

消息格式

消息对象结构

| 字段 | 类型 | 描述 | |------|------|------| | messageId | String | 消息ID | | from | String | 发送者ID | | fromName | String | 发送者名称 | | to | String | 接收者ID(用户ID或群组ID) | | content | String | 消息内容 | | chatType | Number | 聊天类型(0:私聊,1:群聊) | | msgType | Number | 消息类型(0:文本,1:图片,等) | | timestamp | Number | 消息时间戳 | | data | Object/String | 额外数据(JSON对象或字符串) |

集成流程说明

要快速集成IM SDK到您的应用,请遵循以下步骤:

  1. 安装SDK:

    • 通过NPM安装: npm install comind-im-client-sdk --save
    • 或直接在HTML中引入
  2. 配置环境:

    • 配置Socket.IO服务器地址
    • 配置API服务器地址
  3. 初始化SDK:

    • 创建SDK实例
    • 注册必要的事件监听器
  4. 用户认证:

    • 获取认证令牌
    • 连接到服务器
  5. 开始通信:

    • 发送/接收私聊消息
    • 发送/接收群聊消息
    • 管理群组

示例应用场景

场景一:一对一聊天应用

// 初始化SDK
const imClient = new ImClient({
  serverUrl: 'http://your-socket-server:9998',
  apiServer: 'http://your-api-server:8890'
});

// 注册事件
imClient.on('imchat', (message) => {
  if (message.chatType === 0) {
    // 显示私聊消息在UI上
    addMessageToUI(message);
  }
});

// 获取令牌并连接
async function connect() {
  const token = await imClient.getToken({
    apiServer: 'http://your-api-server:8890',
    appId: 'your-app-id',
    appSecret: 'your-app-secret',
    userId: 'current-user-id',
    userName: 'Current User'
  });
  
  await imClient.connect({
    serverUrl: 'http://your-socket-server:9998'
  });
  
  console.log('连接成功');
}

// 发送消息
async function sendMessage(content, recipientId) {
  const result = await imClient.sendPrivateMessage({
    content: content,
    recipientId: recipientId
  });
  
  console.log('消息已发送', result.messageId);
}

场景二:群组聊天应用

// 初始化SDK
const imClient = new ImClient({
  serverUrl: 'http://your-socket-server:9998',
  apiServer: 'http://your-api-server:8890'
});

// 注册事件
imClient.on('imchat', (message) => {
  if (message.chatType === 1) {
    // 显示群聊消息在UI上
    addGroupMessageToUI(message);
  }
});

// 获取令牌并连接
async function connect() {
  const token = await imClient.getToken({
    apiServer: 'http://your-api-server:8890',
    appId: 'your-app-id',
    appSecret: 'your-app-secret',
    userId: 'current-user-id',
    userName: 'Current User'
  });
  
  await imClient.connect({
    serverUrl: 'http://your-socket-server:9998'
  });
  
  // 获取群组列表
  const groups = await imClient.getGroupList({
    apiServer: 'http://your-api-server:8890'
  });
  
  displayGroups(groups);
}

// 发送群聊消息
async function sendGroupMessage(content, groupId) {
  const result = await imClient.sendGroupMessage({
    content: content,
    groupId: groupId
  });
  
  console.log('群聊消息已发送', result.messageId);
}

注意事项

  1. 初始化顺序:必须先获取令牌并连接成功后才能使用消息发送和群组管理功能
  2. apiServer参数:创建ImClient实例时,应提供apiServer选项,这对于后续的API调用(如获取群组列表)至关重要
  3. Socket.IO依赖:SDK依赖Socket.IO客户端库(v2.3.0),使用前请确保已导入
  4. 异步处理:所有API方法都返回Promise对象,请使用async/await或then/catch处理结果
  5. 消息监听:对于实时消息通知,建议监听imchat事件来统一处理所有类型的消息
  6. 历史消息:历史消息按时间戳排序,可能需要额外处理排序逻辑
  7. 重连机制:在断网情况下SDK会自动尝试重连,请设置适当的重连参数
  8. 错误处理:建议使用try-catch捕获API调用可能产生的异常
  9. Token过期:认证令牌有过期时间,应处理token过期的情况,及时重新获取
  10. 环境兼容:SDK支持浏览器和Node.js环境,但在某些特定环境下可能需要额外配置