即时通讯客户端SDK,提供连接、鉴权、消息发送、群组管理等功能。
npm install comind-im-client-sdk --save
<!-- 先引入Socket.IO客户端库 -->
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@2.3.0/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'
选项 | 类型 | 默认值 | 描述 |
---|---|---|---|
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到您的应用,请遵循以下步骤:
-
安装SDK:
- 通过NPM安装:
npm install comind-im-client-sdk --save
- 或直接在HTML中引入
- 通过NPM安装:
-
配置环境:
- 配置Socket.IO服务器地址
- 配置API服务器地址
-
初始化SDK:
- 创建SDK实例
- 注册必要的事件监听器
-
用户认证:
- 获取认证令牌
- 连接到服务器
-
开始通信:
- 发送/接收私聊消息
- 发送/接收群聊消息
- 管理群组
场景一:一对一聊天应用
// 初始化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);
}
- 初始化顺序:必须先获取令牌并连接成功后才能使用消息发送和群组管理功能
- apiServer参数:创建ImClient实例时,应提供apiServer选项,这对于后续的API调用(如获取群组列表)至关重要
- Socket.IO依赖:SDK依赖Socket.IO客户端库(v2.3.0),使用前请确保已导入
- 异步处理:所有API方法都返回Promise对象,请使用async/await或then/catch处理结果
- 消息监听:对于实时消息通知,建议监听imchat事件来统一处理所有类型的消息
- 历史消息:历史消息按时间戳排序,可能需要额外处理排序逻辑
- 重连机制:在断网情况下SDK会自动尝试重连,请设置适当的重连参数
- 错误处理:建议使用try-catch捕获API调用可能产生的异常
- Token过期:认证令牌有过期时间,应处理token过期的情况,及时重新获取
- 环境兼容:SDK支持浏览器和Node.js环境,但在某些特定环境下可能需要额外配置