初始配置

  • React Native

更新时间

RTM SDK API 参考介绍了实时消息相关 API 的接口描述、接口方法、基本用法示例代码和返回值。

在初始化 RTM 客户端实例之前,你需要首先在代码中引入 RTM React Native SDK:

使用 yarn 或者 npm 安装 React Native SDK。

Shell
# 使用 yarn 安装
yarn add agora-react-native-rtm

# 使用 npm 安装
npm i --save agora-react-native-rtm

RtmConfig

接口描述

RtmConfig 用于设置 RTM 初始化时配置其他额外属性,这些配置属性会在整个 RTM 客户端的生命周期中生效,影响 RTM 客户端的行为。

接口方法

你可以通过以下方式创建 RtmConfig 实例:

TypeScript
new RtmConfig({
    userId: uid,
    appId: appId,
})
属性类型是否必填默认值描述
appIdstring必填-声网控制台创建项目时获得的 App ID。
userIdstring必填-用户 ID,用于标识用户或设备。为区分各用户和设备,你需要确保 userId 全局唯一,并且在用户或设备的生命周期内保持不变。
areaCodeRtmAreaCode选填glob服务区域代码,你可以根据自己业务部署的区域进行选择,详见 RtmAreaCode。
protocolTypeRtmProtocolType选填tcpUdp消息传输协议类型。RTM 默认使用一路 TCP 和一路 UDP 协议进行传输,你可以根据需要修改协议类型。详见 RtmProtocolType。
presenceTimeoutnumber选填300Presence 的超时时间。单位为秒,取值范围为 [5,300]。即 RTM 服务器在判定客户端超时后,延迟多久向其他用户发送 remoteTimeout 事件通知。如果客户端在该参数设置的时间内重新建立连接并返回频道,则 RTM 服务器不会向频道中其他人发送 remoteTimeout 事件通知,也不会删除该用户的临时用户数据。
heartbeatIntervalnumber选填5

SDK 心跳时间。单位为秒,取值范围为 [5,1800]。即客户端向 RTM 服务器发送心跳包的时间间隔。如果客户端在该参数设置的时间内没有向 RTM 服务器发送心跳包,则 RTM 服务器会判定客户端超时。

信息

该参数会影响 PCU 计数,从而影响计费。

useStringUserIdboolean选填true

是否使用 String 类型的用户 ID:

  • true: 使用 String 类型的用户 ID。
  • false: 使用 Uint 类型的用户 ID,SDK 会自动将 String 类型的 userId 属性转换为 Uint 类型。该设置下,你需要在 userId 属性中传入内容为数值的字符串(例如 "1234567"),否则方法会调用失败。

当同时使用声网 RTC 和 RTM 产品时,需要确保 userId 一致。

eventHandlerIRtmEventHandler必填-RTM 事件通知监听函数设置。详见事件监听。
logConfigRtmLogConfig选填-本地日志存储的大小、位置和日志等级等配置属性。
proxyConfigRtmProxyConfig选填-当使用 RTM 的 Proxy 功能时,需要配置此参数。
encryptionConfigRtmEncryptionConfig选填-当使用 RTM 端侧加密功能时,需要配置此项参数。
privateConfigRtmPrivateConfig选填-当使用 RTM 的私有化部署功能时,需要配置此项参数。
表格内容超出当前宽度,可横向滚动查看更多列。

RtmLogConfig

RtmLogConfig 实例用来设置和存储本地日志文件 agora.log。在调试阶段,通过日志保存和跟踪 App 运行状态,你可以极大的提升效率。如果遇到复杂问题并需要声网技术人员协助调查,你需要提供该日志信息。RtmLogConfig 包含以下属性:

属性类型是否必填默认值描述
filePathstring选填-日志存储路径。
fileSizeInKBnumber选填1024

日志文件大小,单位为 KB,取值范围为 [128,1024]。

  • 如果你填入的值小于 128,则 SDK 按照 128 设置。
  • 如果你填入的值大于 1024,则 SDK 按照 1024 设置。
levelRtmLogLevel选填info日志信息的输出等级,详见 RtmLogLevel。
表格内容超出当前宽度,可横向滚动查看更多列。

RtmProxyConfig

RtmProxyConfig 实例用来设置客户端 Proxy 服务代理等相关属性。在一些网络服务受限的环境下,你可能需要使用此功能。

信息

你需要妥善保管好你的 Proxy 用户名和密码。RTM 不会以任何方式解析、存储、转发你的用户名和密码。此外,如果你在 App 运行过程中修改 Proxy 的设置,该设置要重启 RTM Client 后才能生效。

RtmProxyConfig 包含以下属性:

属性类型是否必填默认值描述
proxyTypeRtmProxyType选填noneProxy 协议类型。详见 RtmProxyType。
serverstring选填-Proxy 服务器域名或 IP 地址。
portnumber选填-Proxy 监听端口。
accountstring选填-Proxy 登录账号。
passwordstring选填-Proxy 登录密码。
表格内容超出当前宽度,可横向滚动查看更多列。

RtmEncryptionConfig

RtmEncryptionConfig 实例用来设置客户端加密所需要的属性。成功设置加密方式、加密密钥等属性后,用户发送的所有消息或者设置的所有状态都会在客户端自动加密和解密。

信息

一旦设置了加密,所有用户必须使用相同的加密模式和密钥,否则数据无法互通。

RtmEncryptionConfig 包含以下属性:

属性类型是否必填默认值描述
encryptionModeRtmEncryptionMode选填none加密方式。详见 RtmEncryptionMode。
encryptionKeystring选填-用户自定义加密密钥,长度无限制。声网推荐使用 32 字节的密钥。
encryptionSaltnumber[]选填null用户自定义加密盐,长度为 32 字节。声网推荐你在服务端使用 OpenSSL 生成盐。
表格内容超出当前宽度,可横向滚动查看更多列。

RtmPrivateConfig

RtmPrivateConfig 实例用来设置私有化部署所需要的属性。包含以下属性:

属性类型是否必填默认值描述
serviceTypeRtmServiceType选填none服务类型。详见 RtmServiceType。
accessPointHostsstring[]选填-服务器的地址数组,数组中支持填写域名或 IP 地址。
accessPointHostsCountnumber选填0服务器地址数量。
表格内容超出当前宽度,可横向滚动查看更多列。

基本用法

TypeScript
const rtmConfig = new RtmConfig({
    encryptionMode : EncryptionMode.AES_256_GCM,
    salt : yourSalt,
    cipherKey : "yourCipherKey",
    presenceTimeout : 300,
    logUpload : true,
    logLevel : "debug",
    cloudProxy : false,
    useStringUserId : false,
    privateConfig: {
        serviceType: ["MESSAGE", "STREAM"]
    },
    heartbeatInterval: 5
});

createAgoraRtmClient

接口描述

调用 createAgoraRtmClient 方法创建并初始化 RTM Client 实例。

信息

  • 创建并初始化客户端实例需要在调用 RTM 的其他 API 之前进行。
  • 为区分各用户和设备,你需要确保 userId 全局唯一,并且在用户或设备的生命周期内保持不变。

接口方法

你可以通过以下方式创建并初始化实例:

TypeScript
createAgoraRtmClient(config: RtmConfig): RTMClient
参数类型是否必填默认值描述
configRtmConfig必填-初始化 RTM Client 的配置参数。详见 RtmConfig。
表格内容超出当前宽度,可横向滚动查看更多列。

基本用法

TypeScript
const rtm = createAgoraRtmClient(
    new RtmConfig({
        userId: uid,
        appId: appId,
    })
);

返回值

一个 RTM 客户端实例,用以在后续调用 RTM 其他 API。

事件监听

接口描述

RTM 总共有 7 种事件通知类型,如下表所示:

事件类型描述
message接收用户所订阅的 Message Channel 及 Topic 中的所有消息事件通知。
presence接收用户所订阅的 Message Channel 及加入的 Stream Channel 中所有的 Presence 事件通知。
topic接收用户所加入的 Stream Channel 中所有 Topic 变更事件通知。
storate接收用户所订阅的 Message Channel 及加入的 Stream Channel 中所有的 Channel Metadata 事件通知,及订阅用户的 User Metadata 事件通知。
lock接收用户所订阅的 Message Channel 及加入的 Stream Channel 中所有的 Lock 事件通知。
linkstate接收客户端网络连接状态变更的事件通知。
tokenPrivilegeWillExpire接收客户端 Token 将要过期的事件通知。
表格内容超出当前宽度,可横向滚动查看更多列。

添加监听

你可以在初始化时添加一个事件监听对象,也可以在 App 生命周期的任意时间调用 addEventListener 方法添加一个或多个事件监听对象。

添加监听

你可以调用 addEventListener 方法监听指定的事件通知。示例代码如下:

TypeScript
// add the message event listener

// Message
rtm.addEventListener("message", event => {
    const channelType = event.channelType;      // Channel type: "STREAM", "MESSAGE", or "USER"
    const channelName = event.channelName;      // The channel from which this message originates
    const topic = event.topicName;              // The Topic from which this message originates, valid when channelType is "STREAM"
    const messageType = event.messageType;      // Message type: "STRING" or "BINARY"
    const customType = event.customType;        // User-defined type
    const publisher = event.publisher;          // Message publisher
    const message = event.message;              // Message payload
    const timestamp = event.timestamp;          // Event timestamp
});
// Presence
rtm.addEventListener("presence", event => {
    const action = event.eventType;             // Action type: 'SNAPSHOT', 'INTERVAL', 'JOIN', 'LEAVE', 'TIMEOUT', 'STATE_CHANGED', 'OUT_OF_SERVICE'
    const channelType = event.channelType;      // Channel type: "STREAM", "MESSAGE", or "USER"
    const channelName = event.channelName;      // The channel from which this event originates
    const publisher = event.publisher;          // The user who triggered this event
    const states = event.stateChanged;          // User state payload, only for stateChanged event
    const interval = event.interval;            // Interval payload, only for interval event
    const snapshot = event.snapshot;            // Snapshot payload, only for snapshot event
    const timestamp = event.timestamp;          // Event timestamp
});
// Topic
rtm.addEventListener("topic", event => {
    const action = event.evenType;              // Action type: 'SNAPSHOT', 'JOIN', 'LEAVE'
    const channelName = event.channelName;      // The channel from which this event originates
    const publisher = event.userId;             // The user who triggered this event
    const topicInfos = event.topicInfos;        // Topic information payload
    const totalTopics = event.totalTopics;      // Total number of topics
    const timestamp = event.timestamp;          // Event timestamp
});
// Storage
rtm.addEventListener("storage", event => {
    const channelType = event.channelType;      // Channel type: "STREAM", "MESSAGE", or "USER"
    const channelName = event.channelName;      // The channel from which this event originates
    const publisher = event.publisher;          // The user who triggered this event
    const storageType = event.storageType;      // Storage category: 'USER' or 'CHANNEL'
    const action = event.eventType;             // Action type: "SNAPSHOT", "SET", "REMOVE", "UPDATE", or "NONE"
    const data = event.data;                    // Payload: 'USER_METADATA' or 'CHANNEL_METADATA'
    const timestamp = event.timestamp;          // Event timestamp
});

// Lock
rtm.addEventListener("lock", event => {
    const channelType = event.channelType;      // Channel type: "STREAM", "MESSAGE", or "USER"
    const channelName = event.channelName;      // The channel from which this event originates
    const publisher = event.publisher;          // The user who triggered this event
    const action = event.evenType;              // Action type: 'SET', 'REMOVED', 'ACQUIRED', 'RELEASED', 'EXPIRED', 'SNAPSHOT'
    const lockName = event.lockName;            // The lock affected
    const ttl = event.ttl;                      // Time-to-live of this lock
    const snapshot = event.snapshot;            // Snapshot payload
    const owner = event.owner;                  // Owner of this lock
    const timestamp = event.timestamp;          // Event timestamp
});
// Link State Change
rtm.addEventListener('linkState', event => {
    const currentState = event.currentState;
    const previousState = event.previousState;
    const serviceType = event.serviceType;
    const operation = event.operation;
    const reason = event.reason;
    const reasonCode = event.reasonCode;
    const affectedChannels = event.affectedChannels;
    const unrestoredChannels = event.unrestoredChannels;
    const timestamp = event.timestamp;
    const isResumed = event.isResumed;
});
// Token Privilege Will Expire
rtm.addEventListener("tokenPrivilegeWillExpire", (channelName) => {
    const channelName = channelName;            // The channel whose token will expire
});

删除监听

如果你不再需要关注某个事件监听对象,但仍需关注其他事件监听对象,你可以调用 removeEventListener 方法删除指定的事件监听对象。

TypeScript
rtm.removeEventListener("tokenPrivilegeWillExpire", yourhandler);

login

接口描述

创建并初始化 RTM 实例之后,你需要执行 login 操作以登录 RTM 服务。登录成功将使客户端与 RTM 服务器建立起长连接,之后客户端才能正常访问 RTM 资源。

信息

用户成功登录 RTM 服务后,应用的 PCU 会增加,这将影响你的账单数据。

接口方法

你可以通过以下方法登录 RTM 系统:

TypeScript
login(options?: LoginOptions): Promise<LoginResponse>;
参数类型是否必填默认值描述
optionsobject必填-登录选项。
表格内容超出当前宽度,可横向滚动查看更多列。

options 对象包含以下属性:

属性类型是否必填默认值描述
tokenstring选填-

初始化 RTM 客户端的 Token。

  • 如果你的项目开启了 Token 鉴权,你可以填入 RTM 临时 Token 或 Token 服务器生成的 RTM 正式 Token。详见客户端鉴权和部署 RTM Token 服务器。
  • 如果你的项目未开启 Token 鉴权,你可以不填,或填入开通了 RTM 服务的项目 App ID。
表格内容超出当前宽度,可横向滚动查看更多列。

基本用法

TypeScript
try{
    const result = await rtm.login({ token: "your_token" });
    console.log(result);
} catch (status){
    console.log(status);
}

返回值

如果方法调用成功,则返回一个 LoginResponse 类型数据:

TypeScript
type LoginResponse {
    timestamp: number;         // 预留字段
}

如果方法调用失败,则返回一个 ErrorInfo 类型数据:

TypeScript
type ErrorInfo = {
    error: boolean;        // 本次操作是否出错
    reason: string;        // 本次操作的 API 名称
    operation: string;     // 错误码
    errorCode: number;     // 错误描述
};

你可以通过检索 errorCode 字段的错误码了解错误原因,并找到对应的解决方法。

logout

接口描述

当你不再需要操作后,可以登出系统。本操作会影响你账单中的 PCU 计费项。

接口方法

你可以通过以下接口退出登录:

TypeScript
logout(): Promise<LogoutResponse>;

基本用法

TypeScript
try{
    const result = await rtm.logout();
    console.log(result);
} catch (status){
    console.log(status);
}

返回值

如果方法调用成功,则返回一个 LogoutResponse 类型数据:

TypeScript
type LogoutResponse {
    timestamp: number;        // 预留字段
}

如果方法调用失败,则返回一个 ErrorInfo 类型数据:

TypeScript
type ErrorInfo = {
    error: boolean;        // 本次操作是否出错
    reason: string;        // 本次操作的 API 名称
    operation: string;     // 错误码
    errorCode: number;     // 错误描述
};

你可以通过检索 errorCode 字段的错误码了解错误原因,并找到对应的解决方法。