IMLib 集成

IMLib 是即时通讯核心 SDK,提供连接、消息、会话、群组、聊天室、好友等能力,不包含 UI。本页以 5 个步骤完成接入。

1. 导入 SDK​

npm install @ni-paas/im-web
# impaas_imlib 尚未发布到 pub.dev,用 pubspec.yaml 的 path 依赖
# dependencies:
#   impaas_imlib:
#     path: /path/to/repo/sdk/flutter/imlib
flutter pub get
implementation("io.nipaas:imlib:1.0.0")
npm install @ni-paas-im/electron
cargo add im-sdk   # 或链接 libim_sdk + include/im_sdk.h

2. 初始化​

import { createClient } from '@ni-paas/im-web';

const client = createClient({
  appkey: 'YOUR_APP_KEY',
  serverUrl: 'https://im.example.com',
});
import 'package:impaas_imlib/impaas_imlib.dart';

final engine = await RCIMIWEngine.create(
  'YOUR_APP_KEY',
  RCIMIWEngineOptions.create(naviServer: 'https://im.example.com'),
);
val options = IMClientOptions(appkey = "YOUR_APP_KEY", serverUrl = "https://im.example.com")
val client = IMClient.init(context, options)
import { initService } from '@ni-paas-im/electron/main';
import { createClient, Events } from '@ni-paas-im/electron';

initService({ appkey: 'YOUR_APP_KEY', dbPath: './im.db' });
const client = createClient({ appkey: 'YOUR_APP_KEY' });
im_client_t* client = im_client_new("YOUR_APP_KEY", "https://im.example.com");
if (!client) { /* 初始化失败 */ }

3. 建立连接​

import { Events } from '@ni-paas/im-web';

client.addEventListener(Events.CONNECTED, () => console.log('connected'));
client.addEventListener(Events.DISCONNECT, (info) => console.warn('disconnected', info));

const res = await client.connect('USER_TOKEN');
if (res.code !== 0) throw new Error(res.msg);
engine.onConnectionStatusChanged = (status) => print('连接状态:$status');
final code = await engine.connect('USER_TOKEN', 10);
if (code != 0) throw Exception('connect failed: $code');
client.addEventListener(IMClientEvent.CONNECTED) { /* connected */ }
client.connect("USER_TOKEN", object : ConnectCallback {
    override fun onSuccess(userId: String) { /* 连接成功 */ }
    override fun onError(error: IMError) { /* 处理错误 */ }
})
const res = await client.connect('USER_TOKEN');
if (res.code !== 0) throw new Error(res.msg);
client.addEventListener(Events.CONNECTED, () => console.log('connected'));
char userId[64];
int rc = im_client_connect(client, "USER_TOKEN", userId, sizeof(userId));
if (rc != 0) { /* 处理错误码 */ }

4. 收发消息​

import { ConversationType, Events } from '@ni-paas/im-web';

client.addEventListener(Events.MESSAGES, (messages) => {
  for (const msg of messages) console.log(msg.conversationType, msg.content);
});

const sent = await client.sendTextMessage(ConversationType.PRIVATE, 'user2', '你好,NI PaaS');
engine.onMessageReceived = (message, left, offline, hasPackage) {
  for (final msg in messages) print(msg.content);
});
final sent = await engine.sendTextMessage(1, 'user2', '你好,NI PaaS');
client.addEventListener(IMClientEvent.MESSAGES) { event ->
    // event 为收到的消息列表
}
client.sendTextMessage(ConversationType.PRIVATE, "user2", "你好,NI PaaS", null, object : SendMessageCallback {
    override fun onSuccess(message: Message) { /* 发送成功 */ }
    override fun onError(error: IMError) { /* 处理错误 */ }
})
const sent = await client.sendTextMessage(ConversationType.PRIVATE, 'user2', '你好,NI PaaS');
char messageId[128];
int rc = im_client_send_text(client, 1, "user2", "你好,NI PaaS", NULL, messageId, sizeof(messageId));

5. 会话列表与历史消息​

const conversations = await client.getConversationList();
const history = await client.getHistoryMessages(ConversationType.PRIVATE, 'user2', { limit: 20 });
await client.clearUnreadCount(ConversationType.PRIVATE, 'user2');
final conversations = await engine.getConversationList();
final history = await engine.getHistoryMessages(1, 'user2', limit: 20);
await engine.clearUnreadCount(1, 'user2');
client.getConversationList(ResultCallback { list -> /* 渲染会话列表 */ })
client.getHistoryMessages(ConversationType.PRIVATE, "user2", 20, null, ResultCallback { page -> /* ... */ })

6. 事件与生命周期​

务必在页面销毁时移除监听,避免重复回调与内存泄漏。

事件触发时机建议处理
CONNECTING开始连接展示连接中状态
CONNECTED连接成功且离线补发完成刷新会话列表
DISCONNECT连接断开停止发送、提示网络异常
SUSPEND服务端主动挂起(多端互踢等)引导重新登录
MESSAGES收到消息按会话聚合、更新未读
CONVERSATION会话变更更新会话列表排序
MESSAGE_RECALLED消息被撤回替换消息占位
READ_RECEIPT已读回执更新刷新已读状态
TYPING对方正在输入展示输入状态
KICKED被踢下线提示并清理本地会话
注意

Token 由业务服务签发并下发,禁止在客户端硬编码 AppSecret;Token 泄露时调用服务端接口吊销。

下一步​