# 初始配置 (/zh-CN/api-reference/rtm/react-native/configuration) > For AI agents: see the complete documentation index at [llms.txt](/llms.txt). 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] ### 接口描述 [#接口描述] `RtmConfig` 用于设置 RTM 初始化时配置其他额外属性,这些配置属性会在整个 RTM 客户端的生命周期中生效,影响 RTM 客户端的行为。 ### 接口方法 [#接口方法] 你可以通过以下方式创建 `RtmConfig` 实例: ```typescript new RtmConfig({ userId: uid, appId: appId, }) ``` | 属性 | 类型 | 是否必填 | 默认值 | 描述 | | --- | --- | --- | --- | --- | | `appId` | string | 必填 | - | 声网控制台创建项目时获得的 App ID。 | | `userId` | string | 必填 | - | 用户 ID,用于标识用户或设备。为区分各用户和设备,你需要确保 `userId` 全局唯一,并且在用户或设备的生命周期内保持不变。 | | `areaCode` | `RtmAreaCode` | 选填 | `glob` | 服务区域代码,你可以根据自己业务部署的区域进行选择,详见 [`RtmAreaCode`](/zh-CN/api-reference/rtm/react-native/enumv#rtmareacode)。 | | `protocolType` | `RtmProtocolType` | 选填 | `tcpUdp` | 消息传输协议类型。RTM 默认使用一路 TCP 和一路 UDP 协议进行传输,你可以根据需要修改协议类型。详见 [`RtmProtocolType`](/zh-CN/api-reference/rtm/react-native/enumv#rtmprotocoltype)。 | | `presenceTimeout` | number | 选填 | `300` | Presence 的超时时间。单位为秒,取值范围为 [5,300]。即 RTM 服务器在判定客户端超时后,延迟多久向其他用户发送 `remoteTimeout` 事件通知。如果客户端在该参数设置的时间内重新建立连接并返回频道,则 RTM 服务器不会向频道中其他人发送 `remoteTimeout` 事件通知,也不会删除该用户的临时用户数据。 | | `heartbeatInterval` | number | 选填 | `5` | [configuration-rn-html-0-6-4 details](#table-slot-configuration-rn-html-0-6-4) | | `useStringUserId` | boolean | 选填 | `true` | [configuration-rn-html-0-7-4 details](#table-slot-configuration-rn-html-0-7-4) | | `eventHandler` | `IRtmEventHandler` | 必填 | - | RTM 事件通知监听函数设置。详见[事件监听](#事件监听)。 | | `logConfig` | `RtmLogConfig` | 选填 | - | 本地日志存储的大小、位置和日志等级等配置属性。 | | `proxyConfig` | `RtmProxyConfig` | 选填 | - | 当使用 RTM 的 Proxy 功能时,需要配置此参数。 | | `encryptionConfig` | `RtmEncryptionConfig` | 选填 | - | 当使用 RTM 端侧加密功能时,需要配置此项参数。 | | `privateConfig` | `RtmPrivateConfig` | 选填 | - | 当使用 RTM 的私有化部署功能时,需要配置此项参数。 | **configuration-rn-html-0-6-4 details** SDK 心跳时间。单位为秒,取值范围为 [5,1800]。即客户端向 RTM 服务器发送心跳包的时间间隔。如果客户端在该参数设置的时间内没有向 RTM 服务器发送心跳包,则 RTM 服务器会判定客户端超时。 :::info[信息] 该参数会影响 PCU 计数,从而影响计费。 ::: **configuration-rn-html-0-7-4 details** 是否使用 `String` 类型的用户 ID: - `true`: 使用 String 类型的用户 ID。 - `false`: 使用 Uint 类型的用户 ID,SDK 会自动将 `String` 类型的 `userId` 属性转换为 `Uint` 类型。该设置下,你需要在 `userId` 属性中传入内容为数值的字符串(例如 `"1234567"`),否则方法会调用失败。 当同时使用声网 RTC 和 RTM 产品时,需要确保 `userId` 一致。 #### RtmLogConfig [#rtmlogconfig] `RtmLogConfig` 实例用来设置和存储本地日志文件 `agora.log`。在调试阶段,通过日志保存和跟踪 App 运行状态,你可以极大的提升效率。如果遇到复杂问题并需要声网技术人员协助调查,你需要提供该日志信息。`RtmLogConfig` 包含以下属性: | 属性 | 类型 | 是否必填 | 默认值 | 描述 | | --- | --- | --- | --- | --- | | `filePath` | string | 选填 | - | 日志存储路径。 | | `fileSizeInKB` | number | 选填 | `1024` | [configuration-rn-html-1-2-4 details](#table-slot-configuration-rn-html-1-2-4) | | `level` | `RtmLogLevel` | 选填 | `info` | 日志信息的输出等级,详见 [`RtmLogLevel`](/zh-CN/api-reference/rtm/react-native/enumv#rtmloglevel)。 | **configuration-rn-html-1-2-4 details** 日志文件大小,单位为 KB,取值范围为 [128,1024]。 - 如果你填入的值小于 128,则 SDK 按照 128 设置。 - 如果你填入的值大于 1024,则 SDK 按照 1024 设置。 #### RtmProxyConfig [#rtmproxyconfig] `RtmProxyConfig` 实例用来设置客户端 Proxy 服务代理等相关属性。在一些网络服务受限的环境下,你可能需要使用此功能。 :::info[信息] 你需要妥善保管好你的 Proxy 用户名和密码。RTM 不会以任何方式解析、存储、转发你的用户名和密码。此外,如果你在 App 运行过程中修改 Proxy 的设置,该设置要重启 RTM Client 后才能生效。 ::: `RtmProxyConfig` 包含以下属性: | 属性 | 类型 | 是否必填 | 默认值 | 描述 | |-----------|----------------|--------|-------| ----------- | | `proxyType` | `RtmProxyType` | 选填 | `none` | Proxy 协议类型。详见 [`RtmProxyType`](/zh-CN/api-reference/rtm/react-native/enumv#rtmproxytype)。 | | `server` | string | 选填 | - | Proxy 服务器域名或 IP 地址。 | | `port` | number | 选填 | - | Proxy 监听端口。 | | `account` | string | 选填 | - | Proxy 登录账号。 | | `password` | string | 选填 | - | Proxy 登录密码。 | #### RtmEncryptionConfig [#rtmencryptionconfig] `RtmEncryptionConfig` 实例用来设置客户端加密所需要的属性。成功设置加密方式、加密密钥等属性后,用户发送的所有消息或者设置的所有状态都会在客户端自动加密和解密。 :::info[信息] 一旦设置了加密,所有用户必须使用相同的加密模式和密钥,否则数据无法互通。 ::: `RtmEncryptionConfig` 包含以下属性: | 属性 | 类型 | 是否必填 | 默认值 | 描述 | |-----|-------|--------|------------| -------------- | | `encryptionMode` | `RtmEncryptionMode` | 选填 | `none` | 加密方式。详见 [`RtmEncryptionMode`](/zh-CN/api-reference/rtm/react-native/enumv#rtmencrptionmode)。 | | `encryptionKey` | string | 选填 | - | 用户自定义加密密钥,长度无限制。声网推荐使用 32 字节的密钥。 | | `encryptionSalt` | number[] | 选填 | `null` | 用户自定义加密盐,长度为 32 字节。声网推荐你在服务端使用 OpenSSL 生成盐。 | #### RtmPrivateConfig [#rtmprivateconfig] `RtmPrivateConfig` 实例用来设置私有化部署所需要的属性。包含以下属性: | 属性 | 类型 | 是否必填 | 默认值 | 描述 | |-----|-------|--------|------------| ------- | | `serviceType` | `RtmServiceType` | 选填 | `none` | 服务类型。详见 [`RtmServiceType`](/zh-CN/api-reference/rtm/react-native/enumv#rtmservicetype)。 | | `accessPointHosts` | string[] | 选填 | - | 服务器的地址数组,数组中支持填写域名或 IP 地址。 | | `accessPointHostsCount` | number | 选填 | 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] ### 接口描述 [#接口描述-1] 调用 `createAgoraRtmClient` 方法创建并初始化 RTM Client 实例。 :::info[信息] - 创建并初始化客户端实例需要在调用 RTM 的其他 API 之前进行。 - 为区分各用户和设备,你需要确保 `userId` 全局唯一,并且在用户或设备的生命周期内保持不变。 ::: ### 接口方法 [#接口方法-1] 你可以通过以下方式创建并初始化实例: ```typescript createAgoraRtmClient(config: RtmConfig): RTMClient ``` | 参数 | 类型 | 是否必填 | 默认值 | 描述 | | ------ | --------- | ------ | ---- | ---- | | `config` | `RtmConfig` | 必填 | - | 初始化 RTM Client 的配置参数。详见 [`RtmConfig`](#rtmconfig)。 | ### 基本用法 [#基本用法-1] ```typescript const rtm = createAgoraRtmClient( new RtmConfig({ userId: uid, appId: appId, }) ); ``` ### 返回值 [#返回值] 一个 RTM 客户端实例,用以在后续调用 RTM 其他 API。 ## 事件监听 [#事件监听] ### 接口描述 [#接口描述-2] 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` 方法添加一个或多个事件监听对象。 #### 添加监听 [#添加监听-1] 你可以调用 `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 [#login] ### 接口描述 [#接口描述-3] 创建并初始化 RTM 实例之后,你需要执行 `login` 操作以登录 RTM 服务。登录成功将使客户端与 RTM 服务器建立起长连接,之后客户端才能正常访问 RTM 资源。 :::info[信息] 用户成功登录 RTM 服务后,应用的 PCU 会增加,这将影响你的账单数据。 ::: ### 接口方法 [#接口方法-2] 你可以通过以下方法登录 RTM 系统: ```typescript login(options?: LoginOptions): Promise; ``` | 参数 | 类型 | 是否必填 | 默认值 | 描述 | | --- | --- | --- | --- | --- | | `options` | object | 必填 | - | 登录选项。 | `options` 对象包含以下属性: | 属性 | 类型 | 是否必填 | 默认值 | 描述 | | --- | --- | --- | --- | --- | | `token` | string | 选填 | - | [configuration-rn-html-3-1-4 details](#table-slot-configuration-rn-html-3-1-4) | **configuration-rn-html-3-1-4 details** 初始化 RTM 客户端的 Token。 - 如果你的项目开启了 Token 鉴权,你可以填入 [RTM 临时 Token](/zh-CN/realtime-media/rtm/build/rtm-initialization/enable-service#5-获取临时-token) 或 Token 服务器生成的 RTM 正式 Token。详见[客户端鉴权](/zh-CN/realtime-media/rtm/build/authentication-and-connection/user-authentication)和[部署 RTM Token 服务器](/zh-CN/realtime-media/rtm/build/authentication-and-connection/token-generation)。 - 如果你的项目未开启 Token 鉴权,你可以不填,或填入开通了 RTM 服务的项目 App ID。 ### 基本用法 [#基本用法-2] ```typescript try{ const result = await rtm.login({ token: "your_token" }); console.log(result); } catch (status){ console.log(status); } ``` ### 返回值 [#返回值-1] 如果方法调用成功,则返回一个 `LoginResponse` 类型数据: ```typescript type LoginResponse { timestamp: number; // 预留字段 } ``` 如果方法调用失败,则返回一个 `ErrorInfo` 类型数据: ```typescript type ErrorInfo = { error: boolean; // 本次操作是否出错 reason: string; // 本次操作的 API 名称 operation: string; // 错误码 errorCode: number; // 错误描述 }; ``` 你可以通过检索 `errorCode` 字段的[错误码](/zh-CN/realtime-media/rtm/build/troubleshooting)了解错误原因,并找到对应的解决方法。 ## logout [#logout] ### 接口描述 [#接口描述-4] 当你不再需要操作后,可以登出系统。本操作会影响你账单中的 PCU 计费项。 ### 接口方法 [#接口方法-3] 你可以通过以下接口退出登录: ```typescript logout(): Promise; ``` ### 基本用法 [#基本用法-3] ```typescript try{ const result = await rtm.logout(); console.log(result); } catch (status){ console.log(status); } ``` ### 返回值 [#返回值-2] 如果方法调用成功,则返回一个 `LogoutResponse` 类型数据: ```typescript type LogoutResponse { timestamp: number; // 预留字段 } ``` 如果方法调用失败,则返回一个 `ErrorInfo` 类型数据: ```typescript type ErrorInfo = { error: boolean; // 本次操作是否出错 reason: string; // 本次操作的 API 名称 operation: string; // 错误码 errorCode: number; // 错误描述 }; ``` 你可以通过检索 `errorCode` 字段的[错误码](/zh-CN/realtime-media/rtm/build/troubleshooting)了解错误原因,并找到对应的解决方法。