Flutter
Updated
API reference for the Agora Signaling Flutter SDK.
The Signaling SDK API reference is divided into the following sections:
- Setup
- User authentication
- Channels
- Topics
- Messages
- Presence
- Storage
- Lock
- Enumerated types
- Troubleshooting
Setup
The API reference for the Signaling SDK documents interface descriptions, methods, basic usage, and return values of the Signaling APIs.
RtmConfig
Description
Use the RtmConfig to set additional properties for Signaling initialization. These configuration properties will take effect throughout the lifecycle of the Signaling client and affect the behavior of the Signaling client.
Method
You can create RtmConfig instances as follows:
RtmConfig({
int heartbeatInterval,
int presenceTimeout,
bool useStringUserId,
bool ispPolicyEnabled,
RtmProtocolType protocolType,
RtmLogConfig logConfig,
RtmProxyConfig proxyConfig,
RtmEncryptionConfig encryptionConfig,
RtmPrivateConfig privateConfig,
Set<RtmAreaCode> areaCode
})| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
areaCode | RtmAreaCode | Optional | glob | Service area code, you can choose according to the region where your business is deployed. See RtmAreaCode. |
protocolType | RtmProtocolType | Optional | tcpUdp | Protocol types for message transmission. Signaling by default utilizes one-way TCP and one-way UDP protocols for transmission, but you have the flexibility to modify the protocol types based on your requirements. See RtmProtocolType. |
presenceTimeout | int | Optional | 300 | Presence timeout in seconds, and the value range is [5,300]. This parameter refers to the delay imposed by the Signaling server before sending a remoteTimeout event notification to other users once it determines that a client has timed out. If the client reconnects and returns to the channel within the specified time, the Signaling server does not send the remoteTimeout event notification to other participants or delete the temporary user data associated with the user. |
heartbeatInterval | int | Optional | 5 | Heartbeat interval in seconds, and the value range is [5,1800]. This parameter refers to the time interval at which the client sends heartbeat packets to the Signaling server. If the client fails to send heartbeat packets to the Signaling server within the specified time, the Signaling server determines that the client has timed out. Please note that this parameter affects the PCU count, which in turn affects billing. |
useStringUserId | bool | Optional | true | Whether to use string-type user IDs: - true: Use string-type user IDs. - false: Use int-type user IDs. The SDK automatically converts string-type user IDs to int-type ones. In this case, the userId parameter must be a numeric string (for example, "123457"), otherwise initialization fails.When using Agora RTC and Signaling products at the same time, it is necessary to ensure that the userId parameter is consistent. |
ispPolicyEnabled | bool | Optional | false | Whether to enable the ISP policy. In IoT scenarios, devices may be restricted by the Internet Service Provider (ISP). Use this field to configure the SDK connection mode. |
logConfig | RtmLogConfig | Optional | - | Log configuration properties such as the log storage size, storage path, and level. |
proxyConfig | RtmProxyConfig | Optional | - | When using the Proxy feature of Signaling, you need to configure this parameter. |
encryptionConfig | RtmEncryptionConfig | Optional | - | When using the client-side encryption feature of Signaling, you need to configure this parameter. |
privateConfig | RtmPrivateConfig | Optional | - | When using the private deployment feature of Signaling, you need to configure this parameter. |
RtmLogConfig
RtmLogConfig({
String filePath,
int fileSizeInKB,
RtmLogLevel level
})Use the RtmLogConfig instance to configure and store local log files named agora.log. During the debugging phase, you can greatly improve efficiency by storing and tracking the running status of the app through logs. If you encounter complex problems and need Agora technical support to assist with the investigation, you need to provide the log information. RtmLogConfig contains the following properties:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
filePath | String | Optional | - | Log file storage paths. |
fileSizeInKB | int | Optional | 1024 | Log file size in KB, with a value range of [128,1024]. - If the value you enter is less than 128, the SDK sets the value to 128. - If the value you enter is greater than 1024, the SDK sets the value to 1024. |
level | RtmLogLevel | Optional | info | Output level of log information. See RtmLogLevel. |
RtmProxyConfig
RtmProxyConfig({
RtmProxyType proxyType,
String server,
int port,
String account,
String password
})Use the RtmProxyConfig instance to set properties related to the client Proxy service. In some restricted network environments, you might need to use this feature.
Caution
You need to keep your Proxy username and password safe. The Signaling SDK does not parse, store, or forward your username and password in any way. In addition, if you modify the Proxy settings during the app running process, the settings will take effect only after restarting the Signaling client.
RtmProxyConfig contains the following properties:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
proxyType | RtmProxyType | Optional | none | Proxy protocol type. See RtmProxyType. |
server | String | Optional | - | Proxy server domain name or IP address. |
port | int | Optional | 0 | Proxy listening port. |
account | String | Optional | - | Proxy login account. |
password | String | Optional | - | Proxy login password. |
RtmEncryptionConfig
RtmEncryptionConfig({
RtmEncryptionMode encryptionMode,
String encryptionKey,
Uint8List encryptionSalt
})Use the RtmEncryptionConfig instance to set the properties required for the client-side encryption. After successfully setting encryption modes, encryption keys, and other related properties, the SDK automatically encrypts and decrypts all messages sent or all statuses set by the user on the client side.
Caution
Once you set the encryption feature, all users must use the same encryption mode and key, otherwise users cannot communicate with each other.
RtmEncryptionConfig contains the following properties:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
encryptionMode | RtmEncryptionMode | Optional | none | Encryption mode. See RtmEncryptionMode. |
encryptionKey | String | Optional | - | User-defined encryption key, unlimited length. Agora recommends using a 32-byte key. |
encryptionKdfSalt | Uint8List | Optional | null | User-defined encryption salt, length is 32 bytes. Agora recommends using OpenSSL to generate salt on the server side. |
RtmPrivateConfig
RtmPrivateConfig({
Set<RtmServiceType> serviceType,
List<String> accessPointHosts
})Use the RtmPrivateConfig instance to set the properties required for the private deployment.
RtmPrivateConfig contains the following properties:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
serviceType | Set<RtmServiceType> | Optional | - | Service type. See RtmServiceType. |
accessPointHosts | List<String> | Optional | - | An array of server addresses, where you can fill in domain names or IP addresses. |
Basic usage
final proxyConfig = RtmProxyConfig(
protocolType : RtmProxyType.http,
server : "x.x.x.x",
port : 8080,
account : "Tony",
password : "pwd" );
final logConfig = RtmLogConfig(
filePath : "xxxx",
fileSizeInKB : 1024;
leave : RtmLogLevel.info );
final encryptionConfig = RtmEncryptionConfig(
encryptionMode : RtmEncryptionMode.aes256Gcm,
encryptionKey : "XXXXX",
encryptionSalt : [1,2,3,4,5]);
final rtmConfig = RtmConfig(
heartbeatInterval : 10,
presenceTimeout : 5,
proxyConfig : proxyConfig,
logConfig : logConfig,
areaCode : `RtmAreaCode.cn, RtmAreaCode.na`,
encryptionConfig : encryptionConfig );
Initialization
Description
Call the RTM() method to create and initialize the Signaling Client instance.
Information
- You need to create and initialize a client instance before calling other Signaling APIs.
- To distinguish each user or device, you need to ensure that the userId parameter is globally unique and remains unchanged throughout the user or device's lifecycle.
Method
You can create and initialize an instance as follows:
Future<(RtmStatus,RtmClient)> RTM(
String appId,
String userId,
{
RtmConfig rtmConfig
}
)| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
appId | String | Required | - | App ID obtained when creating a project in the Agora Console. |
userId | String | Required | - | User ID for identifying a user or a device. To distinguish each user or device, you need to ensure that the userId parameter is globally unique and remains unchanged throughout the user or device's lifecycle. |
rtmConfig | RtmConfig | Optional | - | Initialize the configuration parameters of the Signaling Client. See RtmConfig. |
Basic usage
final proxyConfig = RtmProxyConfig(
protocolType : RtmProxyType.http,
server : "x.x.x.x",
port : 8080,
account : "Tony",
password : "pwd" );
final logConfig = RtmLogConfig(
filePath : "xxxx",
fileSizeInKB : 1024,
leave : RtmLogLevel.info );
final encryptionConfig = RtmEncryptionConfig(
encryptionMode : RtmEncryptionMode.aes256gcm,
encryptionKey : "XXXXX",
encryptionSalt : [1,2,3,4,5]);
final rtmConfig = RtmConfig(
heartbeatInterval : 10,
presenceTimeout : 5,
proxyConfig : proxyConfig,
logConfig : logConfig,
areaCode : `RtmAreaCode.cn, RtmAreaCode.na`,
encryptionConfig : encryptionConfig );
var (status,rtmClient) = await RTM("myAppId", "Tony", rtmConfig:rtmConfig);
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus,RtmClient)> tuple.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a Signaling client instance for subsequent calls to other Signaling APIs.
Event Listeners
Description
Signaling has a total of 7 types of event notifications, as shown in the following table:
| Event Type | Description |
|---|---|
message | Receive message event notifications in subscribed message channels and subscribed topics. |
presence | Receive presence event notifications in subscribed message channels and joined stream channels. |
topic | Receive all topic event notifications in joined stream channels. |
storage | Receive channel metadata event notifications in subscribed message channels and joined stream channels, and the user metadata event notification of the subscribed users. |
lock | Receive lock event notifications in subscribed message channels and joined stream channels. |
linkState | Receive event notifications when client connection status changes. For details, see LinkStateEvent. |
token | Receive event notifications when the client tokens are about to expire. |
Add event listeners
You can add an event listener object as follows:
rtmClient.addListener({
Function(MessageEvent event)? message = null,
Function(PresenceEvent event)? presence = null,
Function(TopicEvent event)? topic = null,
Function(StorageEvent event)? storage = null,
Function(LockEvent event)? lock = null,
Function(LinkStateEvent event)? linkState = null,
Function(TokenEvent event)? token = null,
})Remove event listeners
You can remove an event listener object as follows:
rtmClient.removeListener({
Function(MessageEvent event) message = null,
})MessageEvent
Message event.
MessageEvent contains the following properties:
| Properties | Type | Description |
|---|---|---|
channelType | RtmChannelType | Channel types. See RtmChannelType. |
messageType | RtmMessageType | Message type. See RtmMessageType. |
channelName | String | Channel name. |
channelTopic | String | Topic name. |
message | Uint8List | Message. |
messageLength | int | Message length. |
publisher | String | User ID of the message publisher. |
customType | String | A user-defined field. Only supports string type. |
timestamp | int | The timestamp when the event occurs. |
PresenceEvent
User presence event.
PresenceEvent contains the following properties:
| Properties | Type | Description |
|---|---|---|
type | RtmPresenceEventType | Presence event type. See RtmPresenceEventType. |
channelType | RtmChannelType | Channel types. See RtmChannelType. |
channelName | String | Channel name. |
publisher | String | User ID of the message publisher. |
stateItems | List<StateItem> | Key-value pair that identifies the user's presence state. |
interval | IntervalInfo | In the Interval state, the aggregated incremental information of event notifications such as user joining, leaving, timeout, and status change in the previous period of the current channel. |
snapshot | SnapshotInfo | When the user first joins the channel, the server pushes the snapshot data of all users in the current channel and their statuses to the user. |
timestamp | int | The timestamp when the event occurs. |
StateItem data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
key | String | Key of the user state. If the specified key already exists, the SDK overwrites the value; if the specified key does not exist, the SDK creates the key-value pair. |
value | String | Value of the user state. |
IntervalInfo contains the following properties:
| Properties | Type | Description |
|---|---|---|
joinUserList | UserList | List of users who joined the channel in the previous cycle. |
leaveUserList | UserList | List of users who left the channel in the previous cycle. |
timeoutUserList | UserList | List of users who timed out joining the channel in the previous cycle. |
userStateList | List<UserState> | List of users whose status has changed in the previous cycle. Contains user ID and status key-value pairs. |
SnapshotInfo contains the following properties:
| Properties | Type | Description |
|---|---|---|
userStateList | List<UserState> | Snapshot information of the user when first joining the channel, including user ID and key-value pairs of status. |
UserList contains the following properties:
| Properties | Type | Description |
|---|---|---|
users | List<String> | User list. |
UserState contains the following properties:
| Properties | Type | Description |
|---|---|---|
userId | String | User ID. |
states | List<StateItem> | List of online users and their temporary state information in a specified channel. |
TopicEvent
Topic event.
TopicEvent contains the following properties:
| Properties | Type | Description |
|---|---|---|
type | RtmTopicEventType | Topic event type. See RtmTopicEventType. |
channelName | String | Channel name. |
publisher | String | User ID. |
topicInfos | List<TopicInfo> | Topic information. |
timestamp | int | The timestamp when the event occurs. |
TopicInfo data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
topic | String | Topic name. |
publishers | List<PublisherInfo> | Message publisher array. |
PublisherInfo data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
publisherUserId | String | User ID of the message publisher. |
publisherMeta | String | Metadata of the message publisher. |
StorageEvent
Storage event.
StorageEvent contains the following properties:
| Properties | Type | Description |
|---|---|---|
channelType | RtmChannelType | Channel types. See RtmChannelType. |
storageType | RtmStorageType | Storage type. See RtmStorageType. |
eventType | RtmStorageEventType | Storage event type. See RtmStorageEventType. |
target | String | User ID or channel name. |
data | * | Metadata item. See ``. |
timestamp | int | The timestamp when the event occurs. |
LockEvent
Lock event.
LockEvent contains the following properties:
| Properties | Type | Description |
|---|---|---|
channelType | RtmChannelType | Channel types. See RtmChannelType. |
eventType | RtmLockEventType | Lock event type. See RtmLockEventType. |
channelName | String | Channel name. |
lockDetailList | List<LockDetail> | Details of lock. |
count | int | Lock count. |
timestamp | int | The timestamp when the event occurs. |
The LockDetail data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
lockName | String | Lock name. |
owner | String | The ID of the user who has a lock. |
ttl | int | The expiration time of the lock. The value is in seconds, ranging from [10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the lock event receives the lockReleased event. |
LinkStateEvent
SDK link state event.
LinkStateEvent data type contains the following properties:
| Parameters | Type | Description |
|---|---|---|
currentState | RtmLinkState | The current link state. See RtmLinkState. |
previousState | RtmLinkState | The previous link state. See RtmLinkState. |
serviceType | RtmServiceType | The network connection type. See RtmServiceType. |
operation | RtmLinkOperation | The operation that triggered the current state transition. See RtmLinkOperation. |
reason | String | The reason of the current state transition. See RtmLinkStateChangeReason. |
affectedChannels | List<String> | The channels affected by the current state transition. |
unrestoredChannels | List<String> | The information about the channels to which subscription or joining has not been restored, including the channel name, channel type, and temporary state data in the channel. Typically, this information is empty. |
isResumed | bool | Within 2 minutes of the disconnection, whether the state transitions from disconnected to connected. true refers to the state has transitioned. |
timestamp | int | The timestamp when the event occurs. |
RtmClient Signaling client instance.
login
Description
After creating and initializing the Signaling instance, you need to perform the login operation to log in to the Signaling service. After successful login, the client establishes a long connection with the Signaling server, and then the SDK allows the client to access Signaling resources.
Information
After the user successfully logs in to the Signaling service, the PCU of the application increases, which affects your billing data.
Method
You can log in to the Signaling system as follows:
Future<(RtmStatus, LoginResult?)> login(String token);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
token | String | Required | - | The token used for logging into the Signaling system. - If your project enables token authentication, you can provide either the Signaling temporary token or the Signaling token generated by your token server. See User authentication and Deploy Signaling token generator. - If your project does not enable token authentication, you can enter an empty string or the App ID of a project that enables Signaling services. |
Basic usage
var (status,response) = await rtmClient.login('your_token');
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, LoginResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
LoginResulttype data, which currently does not contain any fields.
logout
Description
When you no longer need to operate, you can log out of the system. This operation affects the PCU item in your billing data.
Method
You can log out as follows:
Future<(RtmStatus, LogoutResult?)> logout();Basic usage
var (status,response) = await rtmClient.logout();
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, LogoutResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
LogoutResulttype data, which currently does not contain any fields.
releaseLock
Description
Once you no longer need the Signaling service, it is best to destroy the RtmClient instance. Doing so protects you from the performance degradation caused by memory leaks, errors, and exceptions.
Method
You can destroy the RtmClient instance as follows:
Future<RtmStatus> release();Basic usage
var status = await rtmClient.release();Return value
Regardless of whether you call this method successfully, this method returns an RtmStatus type data, with the following field definitions:
class RtmStatus {
bool error; // Whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The API for this operation.
String reason; // A brief description of the error reason for this operation.
}You can refer to the errorCode field in the Error Codes to understand the cause of the error and find the corresponding solution.
User authentication
Authentication is the process of validating the identity of each user before they access a system. Agora uses digital tokens to authenticate users and their privileges.
Based on different transmission connections, the RTM SDK provides two types of services: MESSAGE service and STREAM service. These two services use different tokens and the methods for updating tokens are also different:
MESSAGEservice: Use therenewToken()method under thertmClientinstance to update the token, providing authentication services for features such asMessage Channel,User Channel,Presence,Storage, andLock.STREAMservice: Use therenewToken()method under thestreamChannelinstance to update the token, providing authentication services for features such asStream ChannelandTopic.
Both services will return a token expiration notification in the token event. You can implement the business logic for automatic token renewal by listening to this event. The token is valid for up to 24 hours. Agora recommends that you update the token before it expires. This article describes how to update the token.
For more information on generating and using tokens, see Secure authentication with tokens.
renewToken
Description
To ensure timely token updates, Agora recommends listening for the token callback. See Event listeners for details. Once you successfully add the event listener, when the token is about to expire within 30 seconds, the SDK triggers the token callback to notify the user about the impending token expiration.
- Call
rtmClient.renewToken(String token)to renew the token forMESSAGEservice. - Call
streamChannel.renewToken(String token)to renew the token forSTREAMservice.
Method
You can call the renewToken method as follows:
Future<(RtmStatus, RenewTokenResult?)> renewToken(String token);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
token | String | Required | - | Fill in the corresponding token in this parameter according to the type of service you use. - For the MESSAGE service, fill in a newly generated RTM token.- For the STREAM service, fill in a newly generated RTC token. |
Basic Usage
class TokenResult {
final String status;
final String token;
TokenResult(this.status, this.token);
}
// Define the function to fetch token
Future<TokenResult> fetchToken({required String channelName}) async {
// Request token from the token provider
......
String status = "success";
String token = "your_token_here";
return TokenResult(status, token);
}
rtmClient.addListener({
token:(event) => {
if(event.channelName == '') { // When the channelName in the event is empty, it means the MESSAGE service token is about to expire
var result = await fetchToken(); // Fetch the MESSAGE service token
rtmClient.renewToken(result.token); // Renew the MESSAGE service token
} else { // When the channelName in the event is not empty, it means the STREAM service token is about to expire
var result = await fetchToken(channelName: event.channelName); // Fetch the STREAM service token
streamChannel.renewToken(result.token); // Renew the STREAM service token
}
}
});Return Value
Calling this method returns a tuple of type Future<(RtmStatus, RenewTokenResult?)>.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call is successful, the second item in the tuple returns data of type
RenewTokenResult, defined as follows:
class RenewTokenResult {
final RtmServiceType serverType; // Service type
final String channelName; // Channel name
}Channels
Signaling provides a highly efficient channel management mechanism for data transmission. Any user who subscribes or joins a channel can receive messages and events transmitted within 100 milliseconds. Signaling allows clients to subscribe to hundreds or even thousands of channels. Most Signaling APIs perform actions such as sending, receiving, and encrypting based on channels.
Based on capabilities of Agora, Signaling channels are divided into three types to match different application use-cases:
- Message Channel: Follows the industry-standard Pub/Sub (publish/subscribe) mode. You can send and receive messages within the channel by subscribing to a channel, and do not need to create the channel in advance. There is no limit to the number of publishers and subscribers in a channel.
- User Channel: Based on the Pub/Sub (publish/subscribe) mode for point-to-point messaging. Users can directly send messages to a specified user without subscribing to a channel. To receive messages, users only need to listen to the
messageevent. - Stream Channel: Follows a concept similar to the observer pattern in the industry, where users need to create and join a channel before sending and receiving messages. You can create different topics in the channel, and messages are organized and managed through topics.
RtmClient Signaling client instance
subscribeTopic
Description
Signaling provides event notification capabilities for messages and states. By listening for callbacks, you can receive messages and events within subscribed channels. For information on how to add and set event listeners, see Event Listeners.
By calling the subscribeTopic method, the client can subscribe to a message channel and start receiving messages and event notifications within the channel. After successfully calling this method, users who subscribe to the channel and enable the presence event listener can receive a remoteJoinChannel type of the presence event. See Event Listeners.
Information
This method only applies to message channels.
Method
You can call the subscribeTopic method as follows:
Future<(RtmStatus, SubscribeResult?)> subscribe(
String channelName,
{
bool withMessage = true,
bool withMetadata = false,
bool withPresence = true,
bool withLock = false,
bool beQuiet = false
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
withMessage | bool | Optional | true | Whether to subscribe to message event notifications in the channel. |
withPresence | bool | Optional | true | Whether to subscribe to presence event notifications in the channel. |
withMetadata | bool | Optional | false | Whether to subscribe to storage event notifications in the channel. |
withLock | bool | Optional | false | Whether to subscribe to lock event notifications in the channel. |
beQuiet | bool | Optional | false | Whether to set the silent mode. If you set this parameter as true, the SDK has the following behaviors:- You can still receive other users' event notifications. - Event notifications related to your channel activity such as subscribing or unsubscribing the channel, and actions related to setting, getting, or deleting temporary user states, can not be broadcasted to other users. - When calling the getOnlineUsers method, your information can not be found.- When calling the getUserChannels method, channels that you subscribe in silent mode can not be detected. |
Basic usage
var (status,response) = await rtmClient.subscribe("myChannel", withPresence:true, beQuiet:true);
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, SubscribeResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
SubscribeResulttype data, defined as follows:
class SubscribeResult {
final String channelName; // The channel of the current operation
}unsubscribeTopic
Description
If you no longer need to subscribe to a channel, you can call the unsubscribeTopic method to unsubscribe from the channel. After successfully calling this method, users who subscribe to the channel and enable event listeners can receive the remoteLeaveChannel type of the presence event notification. See Event Listeners.
Information
This method only applies to message channels.
Method
You can call the unsubscribeTopic method as follows:
Future<(RtmStatus, UnsubscribeResult?)> unsubscribe(String channelName);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
Basic usage
var (status,response) = await rtmClient.unsubscribe("myChannel");
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, UnsubscribeResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple will return a
UnsubscribeResulttype data, defined as follows:
class UnsubscribeResult {
final String channelName; // The channel of the current operation
}createAgoraRtmClient
Description
Before using a stream channel, you need to call the createAgoraRtmClient method to create a StreamChannel instance. After successfully creating the instance, you can call its relevant methods to implement functions, such as joining the channel, leaving the channel, sending messages in a topic, and subscribing to messages in a topic.
Information
This method only applies to stream channels.
Method
You can call the createAgoraRtmClient method as follows:
Future<(RtmStatus, StreamChannel?)> createStreamChannel(String channelName);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
Basic usage
var (status, stChannel) = await rtmClient.createStreamChannel("myStChannel");
if (status.error == true) {
print(status);
} else {
print("create Stream Channel Success!");
}Return value
Calling this method returns a Future<(RtmStatus, StreamChannel?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple will return a
StreamChannelinstance object, which can be used to call related API ofStreamChannel.
StreamChannel Stream channel instance
joinTopic
Description
After successfully creating a stream channel, you can call the joinTopic method to join the stream channel.
Once you join the channel, you can implement channel-related functions. At this point, users who subscribe to the channel and add event listeners can receive the following event notifications:
- For the local user:
- The
snapshottype of thepresenceevent. - The
snapshottype of thetopicevent.
- The
- For remote users: The
remoteJoinChanneltype of thepresenceevent.
Information
This method only applies to stream channels.
Method
You can call the joinTopic method as follows:
Future<(RtmStatus, JoinResult?)> join({
String? token,
bool withMetadata = false,
bool withPresence = true,
bool withLock = false,
bool beQuiet = false
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
token | String | Optional | - | The token used for joining a stream channel. - If your project enables token authentication, you can provide either the RTC temporary token or the RTC token generated by your token server. - If your project does not enable token authentication, you can enter an empty string or the App ID of a project that enables RTC and Signaling services. |
withPresence | bool | Optional | true | Whether to subscribe to presence event notifications in the channel. |
withMetadata | bool | Optional | false | Whether to subscribe to storage event notifications in the channel. |
withLock | bool | Optional | false | Whether to subscribe to lock event notifications in the channel. |
beQuiet | bool | Optional | false | Whether to set the silent mode. If you set this parameter as true, the SDK has the following behaviors:- You can still receive other users' event notifications. - Event notifications related to your channel activity such as joining or leaving the channel, and actions related to setting, getting, or deleting temporary user states, can not be broadcasted to other users. - When calling the getOnlineUsers method, your information can not be found.- When calling the getUserChannels method, channels that you subscribe in silent mode can not be detected. |
Basic usage
var (status,response) = await stChannel.join(token:"myToken", withPresence:true);
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, JoinResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple will return a
JoinResulttype data, defined as follows:
class JoinResult {
final String channelName; // The channel of the current operation
final String userId; // The user ID of the current operation
}leaveTopic
Description
If you no longer need to stay in a channel, you can call the leaveTopic method to leave the channel. After leaving the channel, you can no longer receive any messages, states, or event notifications from this channel. At the same time, you can no loger be the topic publisher or subscriber of all topics. If you want to restore your previous publisher role and subscribing relationship, you need to call joinTopic, joinTopic and subscribeTopic methods in order.
After successfully leaving the channel, remote users in the channel can receive the remoteLeaveChannel type of the presence event notification. For details, see Event Listeners.
Information
This method only applies to stream channels.
Method
You can call the leaveTopic method as follows:
Future<(RtmStatus, LeaveResult?)> leave();Basic usage
var (status,response) = await stChannel.leave();
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, LeaveResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple will return a
LeaveResulttype data, defined as follows:
class LeaveResult {
final String channelName; // The channel of the current operation
final String userId; // The user ID of the current operation
}releaseLock
Description
If you no longer need a channel, you can call the releaseLock method to destroy the corresponding stream channel instance and release resources. Calling the releaseLock method does not destroy the stream channel, and it can be re-joined later by calling createAgoraRtmClient and joinTopic again.
Information
This method only applies to stream channels. If you don't call leaveTopic to leave the channel before directly calling releaseLock to destroy the stream channel instance, the SDK automatically calls the leaveTopic and triggers the corresponding event.
Method
You can call the releaseLock method as follows:
Future<RtmStatus> release();Basic usage
var status = await stChannel.release();
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Regardless of whether you call this method successfully, this method returns an RtmStatus type data, with the following field definitions:
class RtmStatus {
bool error; // Whether there is an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The API of this operation.
String reason; // A brief description of the reason for the error in this operation.
}You can refer to the errorCode field in the Error Codes to understand the cause of the error and find the corresponding solution.
Topics
Topic is a data stream management mechanism in stream channels. Users can use topics to subscribe to and distribute data streams, as well as notify events in data streams in stream channels.
Information
Topics only exist in stream channels. Therefore, before using relevant features, you need to create the StreamChannel instance.
StreamChannel Stream channel instance
joinTopic
Description
The purpose of joining a topic is to register as one of the message publishers for the topic, so that the user can send messages in the topic. This operation does not affect whether or not the user becomes a subscriber to the topic.
Information
- Currently, Signaling supports a single client joining up to 8 topics in the same stream channel at a time.
- Before joining a topic, a user needs to create a
StreamChannelinstance and call thejoinTopicmethod to join the channel.
After successfully joining a topic, users who subscribe to that topic and add event listeners can receive the remoteJoinTopic type of the topic event notification. For details, see Event Listeners.
Method
You can call the joinTopic method as follows:
Future<(RtmStatus, JoinTopicResult?)> joinTopic(
String topic,
{
RtmMessageQos qos = RtmMessageQos.unordered,
RtmMessagePriority priority = RtmMessagePriority.normal,
String? meta = '',
bool? syncWithMedia = false
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | String | Required | - | Topic name. |
qos | RtmMessageQos | Optional | unordered | Whether the data transmitted in the topic is ordered. See RtmMessageQos. |
priority | RtmMessagePriority | Optional | normal | The priority of data transmission in the topic compared to other topics in the same channel. See RtmMessagePriority. |
meta | String | Optional | - | Adds additional metadata when joining the topic. |
syncWithMedia | bool | Optional | false | Whether the data sent in this topic is synchronized (timestamp-aligned) with the RTC audio and video data stream of the common channel. |
Basic usage
var (status,response) = await stChannel.joinTopic("myTopic");
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, JoinTopicResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
JoinTopicResultobject, defined as follows:
class JoinTopicResult {
final String channelName; // Channel name
final String userId; // Current userId
final String topic; // Topic name
final String meta; // Additional metadata
}publishTextMessage
Description
Use the publishTextMessage method to send string messages to a topic. Users who have subscribed to the topic and the message publisher in the channel can receive the message within 100 milliseconds. Before calling the publishTextMessage method, users need to join the stream channel, and then register as a message publisher for that topic by calling the joinTopic method.
The messages sent by users are encrypted with TLS during transmission, and data link encryption is enabled by default and cannot be disabled. To achieve a higher level of data security, users can also enable client encryption during initialization. For details, see Setup.
Method
You can call the publishTextMessage method as follows:
Future<(RtmStatus, PublishTopicMessageResult?)> publishTextMessage(
String topic,
String message,
{
int sendTs = 0,
String? customType
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | String | Required | - | Topic name. |
message | String | Required | - | Message payload. |
sendTs | int | Optional | 0 | The timestamp when the SDK sends a message. This parameter is only valid when you set syncWithMedia = true in the joinTopic method. The SDK synchronizes data with RTC audio and video streams based on this timestamp. |
customType | String | Optional | - | A user-defined field. Only supports string type. |
Basic usage
var message = {
type: "poll",
question: "Which option is right?",
answers: {
A: "Apple",
B: "Banana",
C: "Blackberry"
},
sender: "Max"
}
var payload = json.encode(message);
var (status,response) =
await stChannel.publishTextMessage("myTopic", payload, customType:"poll");
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, PublishTopicMessageResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
PublishTopicMessageResultobject, defined as follows:
class PublishTopicMessageResult {
final String channelName; // Channel name
final String topic; // Topic name
}publishBinaryMessage
Description
Use the publishBinaryMessage method to send binary messages to a topic. Users who have subscribed to the topic and the message publisher in the channel can receive the message within 100 milliseconds. Before calling the publishBinaryMessage method, users need to join the stream channel, and then register as a message publisher for that topic by calling the joinTopic method.
The messages sent by users are encrypted with TLS during transmission, and data link encryption is enabled by default and cannot be disabled. To achieve a higher level of data security, users can also enable client encryption during initialization. For details, see Setup.
Method
You can call the publishBinaryMessage method as follows:
Future<(RtmStatus, PublishTopicMessageResult?)> publishBinaryMessage(
String topic,
Uint8List message,
{
int sendTs = 0,
String? customType
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | String | Required | - | Topic name. |
message | Uint8List | Required | - | Message payload. |
sendTs | int | Optional | 0 | The timestamp when the SDK sends a message. This parameter is only valid when you set syncWithMedia = true in the joinTopic method. The SDK synchronizes data with RTC audio and video streams based on this timestamp. |
customType | String | Optional | - | A user-defined field. Only supports string type. |
Basic usage
var payload = [1,2,3,4];
var (status,response) = await stChannel.publishBinaryMessage(
"myTopic",
payload,
customType:"UINT8LIST"
);
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, PublishTopicMessageResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
PublishTopicMessageResultobject, defined as follows:
class PublishTopicMessageResult {
final String channelName; // Channel name
final String topic; // Topic name
}leaveTopic
Description
When you no longer need to publish messages to a topic, to release resources, you can call the leaveTopic method to unregister as a message publisher for that topic. This method does not affect whether or not you subscribe to that topic or any other operations performed by other users on that topic.
After successfully calling this method, users who subscribe to the channel and enable event listeners can receive the remoteLeaveTopic type of the topic event notification. See Event Listeners.
Method
You can call the leaveTopic method as follows:
Future<(RtmStatus, LeaveTopicResult?)> leaveTopic(String topic);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | String | Required | - | Topic name. |
Basic usage
var (status,response) = await stChannel.leaveTopic("myTopic");
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, LeaveTopicResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
LeaveTopicResultobject, defined as follows:
class LeaveTopicResult {
final String channelName; // Channel name
final String userId; // User ID
final String topic; // Topic name
final String meta; // Additional metadata
}subscribeTopic
Description
After joining the channel, you can call the subscribeTopic method to subscribe to the message publisher of the topic in the channel.
subscribeTopic is an incremental method. For example, if you call this method for the first time with a subscribing list of [UserA, UserB], and then call it again with a subscribing list of [UserB, UserC], the final successful subscribing result is [UserA, UserB, UserC].
A user can subscribe to a maximum of 50 topics in each channel, and a maximum of 64 message publishers in each topic. See API usage restrictions.
Method
You can call the subscribeTopic method as follows:
Future<(RtmStatus, SubscribeTopicResult?)> subscribeTopic(
String topic,
{
List<String> users = const []
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | String | Required | - | Topic name. |
users | List<String> | Optional | - | A list of UserId of message publishers that you want to subscribe to. If you do not set this property, you can randomly subscribe to up to 64 users by default. |
Basic usage
Example 1: Subscribe to the specified message publisher in the topic.
var userList = ["Tony","Lily"];
var (status,response) = await stChannel.subscribeTopic("myTopic", users:userList);
if (status.error == true) {
print(status);
} else {
print(response);
}Example 2: Randomly subscribe to 64 message publishers in the topic.
var (status,response) = await stChannel.subscribeTopic("myTopic");
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, SubscribeTopicResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
SubscribeTopicResultobject, defined as follows:
class SubscribeTopicResult {
final String channelName; // Channel name
required this.userId; // User ID
final String topic; // Topic name
final List<String> succeedUsers; // List of successfully subscribed users
final List<String> failedUsers; // List of users that failed to subscribe
}unsubscribeTopic
Description
If you are no longer interested in a specified topic, or no longer need to subscribe to one or more message publishers in the topic, you can call the unsubscribeTopic method to unsubscribe from the topic or the specified message publishers in the topic.
Method
You can call the unsubscribeTopic method as follows:
Future<(RtmStatus, UnsubscribeTopicResult?)> unsubscribeTopic(
String topic,
{
List<String> users = const []
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | String | Required | - | Topic name. |
users | List<String> | Optional | - | A list of UserId of message publishers that you want to unsubscribe from. If you do not set this property, you can randomly unsubscribe from up to 64 users. |
Basic usage
Example 1: Unsubscribe the specified message publisher in the topic
var userList = ["Tony","Lily"];
var (status,response) = await stChannel.unsubscribeTopic("myTopic", users:userList);
if (status.error == true) {
print(status);
} else {
print(response);
}Example 2: Unsubscribe from all message publishers in the topic
var (status,response) = await stChannel.unsubscribeTopic("myTopic");
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, UnsubscribeTopicResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
UnsubscribeTopicResultobject, defined as follows:
class UnsubscribeTopicResult {
final String channelName; // Channel name
final String topic; // Topic name
}getSubscribedUserList
Description
If you need to get the list of publishers that you subscribe to in a specific topic, you can call the getSubscribedUserList method.
Method
You can call the getSubscribedUserList method as follows:
Future<(RtmStatus, GetSubscribedUserListResult?)> getSubscribedUserList(String topic);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | String | Required | - | Topic name. |
Basic usage
var (status,response) = await stChannel.getSubscribedUserList("myTopic");
if (status.error == true) {
print(status);
} else {
print(response);
}Return value
Calling this method returns a Future<(RtmStatus, GetSubscribedUserListResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
GetSubscribedUserListResultobject, defined as follows:
class GetSubscribedUserListResult {
final String channelName; // Channel name
final String topic; // Topic name
final UserList users; // List of successfully subscribed users
}Messages
Sending and receiving messages is the most basic function of the Signaling service. Any message sent by the Signaling server can be delivered to any online subscribing user within 100 ms. Depending on your business requirements, you can send messages to one user only or broadcast messages to multiple users.
Signaling offers 3 types of channels: message channels, user channels, and stream channels. These channel types have the following differences in how messages are transmitted and methods are called:
- Message Channel: The real-time channel. Messages are transmitted through the channel, and the channel is highly scalable. Local users can call the
publishTextMessagemethod, set thechannelTypeparameter tomessage, and set thechannelNameparameter to the channel name to send messages in the channel. The remote users can call thesubscribeTopicmethod to subscribe to the channel and receive messages. - User Channel: The real-time channel. Messages are transmitted to the specified user. Local users can call the
publishTextMessagemethod, set thechannelTypeparameter touser, and set thechannelNameparameter to the user ID to send messages to the specified user. The specified remote users receive messages through themessageevent notifications. - Stream Channel: The streaming transmission channel. Messages are transmitted through the topic. Users need to join a channel first, and then join a topic. Local users can call the
publishTextMessagemethod to send messages in the topic, and remote users can call thesubscribeTopicmethod to subscribe to the topic and receive messages.
This page introduces how to send and receive messages in a message channel or a user channel.
RtmClient Signaling client instance
publishTextMessage
Description
You can directly call the publishTextMessage method to send string messages to all online users subscribed to this channel. Even if you do not subscribe to the channel, you can still send messages in the channel.
Information
The following practices can effectively improve the reliability of message transmission:
- The message payload should be within 32 KB; otherwise, the sending will fail.
- The upper limit of the rate at which messages are sent to a single channel is 60 QPS. If the sending rate exceeds the limit, some messages will be discarded. A lower rate is better, as long as the requirements are met.
After successfully calling this method, the SDK triggers a message event notification. Users who subscribe to the channel and enabled the event listener can receive this event notification. For details, see Event Listeners.
Method
You can call the publishTextMessage method as follows:
Future<(RtmStatus, PublishResult?)> publish(
String channelName,
String message,
{
RtmChannelType channelType = RtmChannelType.message,
String? customType
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Fill in a channel name to send messages in a specified channel, or fill in a user ID to send messages to a specified user. |
message | String | Required | - | Message payload. |
channelType | RtmChannelType | Optional | message | Channel type. See RtmChannelType. |
customType | String | Optional | - | A user-defined field. Only supports string type. |
Basic usage
Example 1: Send string messages to a specified message channel.
var message = {
type: "poll",
question: "Which option is right?",
answers: {
A: "Apple",
B: "Banana",
C: "Blackberry"
},
sender: "Max"
}
var payload = json.encode(message);
var (status,response) =
await rtmClient.publish("myChannel", payload, channelType:RtmChannelType.message, customType:"poll");
if (status.error == true) {
print(status);
} else {
print(response);
}Example 2: Send string messages to a specified user channel.
var message = {
type: "chatInvite",
channel: "this is the channel you are being invited to",
message: "Hi Tony, welcome to the team!"
}
var payload = json.encode(message);
var (status,response) =
await rtmClient.publish("userId", payload, channelType:RtmChannelType.user, customType:"chatInvite");
if (status.error == true) {
print(status);
} else {
print(response);
}Return Values
Calling this method returns a Future<(RtmStatus, PublishResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
PublishResulttype, which currently does not contain any fields.
publishBinaryMessage
Description
You can directly call the publishBinaryMessage method to send binary messages to all online users subscribed to this channel. Even if you do not subscribe to the channel, you can still send messages in the channel.
Information
The following practices can effectively improve the reliability of message transmission:
- The message payload should be within 32 KB; otherwise, the sending will fail.
- The upper limit of the rate at which messages are sent to a single channel is 60 QPS. If the sending rate exceeds the limit, some messages will be discarded. A lower rate is better, as long as the requirements are met.
After successfully calling this method, the SDK triggers a message event notification. Users who subscribe to the channel and enabled the event listener can receive this event notification. For details, see Event Listeners.
Method
You can call the publishBinaryMessage method as follows:
Future<PublishResult> publishBinaryMessage(
String channelName,
Uint8List message,
{
RtmChannelType channelType = RtmChannelType.message,
String? customType
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Fill in a channel name to send messages in a specified channel, or fill in a user ID to send messages to a specified user. |
message | Uint8List | Required | - | Message payload. |
channelType | RtmChannelType | Optional | message | Channel type. See RtmChannelType. |
customType | String | Optional | - | A user-defined field. Only supports string type. |
Basic usage
Example 1: Send binary messages to a specified message channel.
var payload = [1,2,3,4];
var (status,response) = await rtmClient.publishBinaryMessage(
"myChannel",
payload,
channelType:RtmChannelType.message,
customType:"UINT8LIST"
);
if (status.error == true) {
print(status);
} else {
print(response);
}Example 2: Send binary messages to a specified user channel.
var payload = [1,2,3,4];
var (status,response) = await rtmClient.publishBinaryMessage(
"myChannel",
payload,
channelType:RtmChannelType.message,
customType:"UINT8LIST"
);
if (status.error == true) {
print(status);
} else {
print(response);
}Return Values
Calling this method returns a Future<(RtmStatus, PublishResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
PublishResulttype, which currently does not contain any fields.
Receive
Signaling provides event notifications for messages, states, and event changes. By listening for callbacks, you can receive messages and events within subscribed channels. The example code below shows how to receive messages from the user channel:
rtm.addListener(
message: (event) {
print('Received a message from $`event.channelName`');
print('Message Type is $`event.messageType`');
print('Message : $`event.message`');
}
);Message Format Conversion
The message field in MessageEvent is of type Uint8List. When you receive a string message, you can convert it to String type using the utf8.decode() method from the dart:convert library:
// convert Uint8List to String. ! means forced conversion
String message = utf8.decode(event.message!);For information on how to add and set event listeners, see Event Listeners.
Presence
The presence feature provides the ability to monitor user online, offline, and user historical state change. With the Presence feature, you can get real-time access to the following information:
- Real-time event notification when a user joins or leaves a specified channel.
- Real-time event notification when the custom temporary user state changes.
- Query which channels a specified user has joined or subscribed to.
- Query which users have joined a specified channel and their temporary user state data.
Information
Presence applies to both message channels and stream channels.
RtmPresence Presence instance
getOnlineUsers
Description
By calling the getOnlineUsers method, you can query real-time information about the number of online users, the list of online users, and the temporary state of online users in a specified channel.
Method
You can call the getOnlineUsers method as follows:
Future<(RtmStatus, WhoNowResult?) whoNow(
String channelName,
RtmChannelType channelType,
{
bool includeUserId = true,
bool includeState = false,
String? page = ''
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
includeUserId | bool | Optional | true | Whether the returned result includes the user ID of online members. |
includeState | bool | Optional | false | Whether the returned result includes temporary state data of online users. |
page | String | Optional | - | Page number of the returned result. If you do not provide this property, the SDK returns the first page by default. You can check whether there is next page in the returned result. |
Basic usage
var (status, response) = await rtmClient.getPresence.getOnlineUsers(
"myChannel",
RtmChannelType.message,
includeUserId: true,
includeState: true,
page: "myBookMark"
);
if (status.error == true) {
print(status);
} else {
print(response);
}Return Value
Calling this method returns a Future<(RtmStatus, GetOnlineUsersResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
GetOnlineUsersResulttype data, which is defined as follows:
class GetOnlineUsersResult {
final List<UserState> userStateList; // List of user temporary states
final int count; // Length of the user temporary state list
final String nextPage; // Bookmark for the next page of data
}getUserChannels
Description
In use-cases such as statistic analytics and debugging, you may need to know all the channels that a specified user has subscribed to or joined. Call the getUserChannels method to get the list of channels where the specified user is in real time.
Method
You can call the getUserChannels method as follows:
Future<(RtmStatus, GetUserChannelsResult?)> getUserChannels(String userId);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | String | Required | - | User ID. |
Basic usage
var (status, response) = await rtmClient.getPresence.getUserChannels("Tony");
if (status.error == true) {
print(status);
} else {
print(response);
}Return Value
Calling this method returns a Future<(RtmStatus, GetUserChannelsResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
GetUserChannelsResulttype data, which is defined as follows:
class GetUserChannelsResult {
final List<ChannelInfo> channels; // List of channel information
final int count; // Length of the user temporary state list
}setState
Description
To meet different requirements in different business use-cases for setting user states, Signaling provides the setState method to customize the temporary user state. Users can add custom states such as scores, game state, location, mood, and hosting state for themselves.
After successful setup, as long as the user keeps subscribing to the channel and stays online, the custom states can persist in the channel. The setState method sets the temporary user state, and the state disappears when the user leaves the channel. If you need to restore user states when rejoining a channel, you need to cache the data locally in real time. If you want to permanently save user states, Agora recommends you use the setUserMetadata method of the storage function instead.
If a user modifies the temporary user state, Signaling triggers the remoteStateChanged type of the presence event in real time. You can receive the event by subscribing to the channel and configuring the corresponding property.
Method
You can call the setState method as follows:
Future<(RtmStatus, SetStateResult?)> setState(
String channelName,
RtmChannelType channelType,
Map<String, String> state
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
state | Map<String, String> | Required | - | User state key-value pairs. |
Basic usage
var states = {"Name":"Tony","Mode":"Happy"};
var (status, response) = await rtmClient.getPresence.setState(
"myChannel",
RtmChannelType.message,
states
);
if (status.error == true) {
print(status);
} else {
print(response);
}Return Value
Calling this method returns a Future<(RtmStatus, SetStateResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
SetStateResulttype data, which currently does not contain any fields.
getState
Description
To get the temporary user state of a specified user in the channel, you can use the getState method.
Method
You can call the getState method as follows:
Future<(RtmStatus, GetStateResult?)> getState(
String channelName,
RtmChannelType channelType,
String userId
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
userId | String | Required | - | User ID. |
Basic usage
var (state, response) = await rtmClient.getPresence.getState(
"myChannel",
RtmChannelType.message,
"Tony"
);
if (status.error == true) {
print(status);
} else {
print(response);
}Return Value
Calling this method returns a Future<(RtmStatus, GetStateResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
GetStateResulttype data, which is defined as follows:
class GetStateResult {
final UserState state; // User temporary state data
}removeState
Description
When a temporary user state is no longer needed, you can call the removeState method to remove one or more of your temporary states. When the user state is removed, the user who has subscribed to the channel and enabled the presence event listener receives the remoteStateChanged type of presence event notification. See Event Listeners.
Method
You can call the removeState method as follows:
Future<(RtmStatus, RemoveStateResult?)> removeState(
String channelName,
RtmChannelType channelType,
{
List<String> states = const []
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
states | List<String> | Required | - | List of keys to be deleted. If you do not provide this property, the SDK removes all states. |
Basic usage
var states = ["Mode", "Position"];
var (status, response) = await rtmClient.getPresence.removeState(
"channelName",
RtmChannelType.message,
states
);
if (status.error == true) {
print(status);
} else {
print(response);
}Return Value
Calling this method returns a Future<(RtmStatus, RemoveStateResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item in the tuple returns a
RemoveStateResulttype data, which currently does not contain any fields.
Storage
The storage feature provides a dynamic database mechanism that allows developers to dynamically set, store, update, and delete data such as channel metadata and user metadata.
RtmStorage Storage instance
setChannelMetadata
Description
The setChannelMetadata method sets metadata for a message channel or stream channel. A channel can only have one set of metadata, but each set of metadata can have one or more metadata items. If you call this method multiple times, the SDK retrieves the key of the metadata items in turn and apply settings according to the following rules:
- If you set metadata with different
key, the SDK adds each set of metadata in sequence according to the order of the method calls. - If you set metadata with the same
key, thevalueof the last setting overwrites the previous one.
Channel metadata also introduces the version control logic CAS (Compare And Set). This method provides two independent version control fields, and you can set one or more of them according to your actual business use-case:
- Enable version number verification for the entire set of channel metadata by setting the
majorRevisionproperty. - Enable version number verification for a single metadata item by setting the
revisionproperty in theMetadataItemclass.
When setting channel metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:
- The default value of the revision property is
-1, indicating that this method call does not perform any CAS verification. If the channel metadata or metadata item already exists, the latest value overwrites the previous one. If the channel metadata or metadata item does not exist, the SDK creates it. - If the revision property is a positive integer, this method call performs the CAS verification. If the channel metadata or metadata item already exists, the SDK updates the corresponding value after the version number verification succeeds. If the channel metadata or metadata item does not exist, the SDK returns the error code.
After successfully setting channel metadata, users who subscribe to the channel and enable event listeners can receive the channel type of the storage event notification. See Event listeners.
Method
You can call the setChannelMetadata method as follows:
Future<(RtmStatus, SetChannelMetadataResult?)> setChannelMetadata(
String channelName,
RtmChannelType channelType,
List<MetadataItem> metadata,
{
int majorRevision = -1,
bool recordTs = false,
bool recordUserId = false,
String lockName = ''
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | message | Channel types. See RtmChannelType. |
metadata | List<MetadataItem> | Required | - | Metadata item. See MetadataItem . |
majorRevision | int | Optional | -1 | Version control switch: - -1: Disable version verification.- > 0: Enable version verification, only execute the operation if the target version number matches this value. |
recordTs | bool | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | bool | Optional | false | Whether to record the user ID of the editor. |
lockName | String | Optional | '' | Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations. |
The MetadataOptions data type contains the following properties:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
recordTs | bool | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | bool | Optional | false | Whether to record the user ID of the editor. |
Basic usage
var item1 = MetadataItem(
key: 'Apple',
value: '100',
revision: 174298200
);
var item2 = MetadataItem(
key: 'Banana',
value: '200',
revision: 174298100
);
var metadata = [item1,item2];
var (status,response) = await rtmClient.getStorage.setChannelMetadata(
"myChannel",
RtmChannelType.message,
metadata,
majorRevision: 174298222,
recordTs: true,
recordUserId: true,
lockName: "myLock"
)
if (status.error == true) {
print(status);
} else {
print(response);
}Returns
Calling this method returns a Future<(RtmStatus, SetChannelMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call is successful, the second item of the tuple returns a
SetChannelMetadataResulttype data, defined as follows:
class SetChannelMetadataResult {
final String channelName; // The channel being operated on
final RtmChannelType channelType; // The type of the channel being operated on
}getChannelMetadata
Description
The getChannelMetadata method can get the metadata of the specified channel.
Method
You can call the getChannelMetadata method as follows:
Future<(RtmStatus, GetChannelMetadataResult?)> getChannelMetadata(
String channelName,
RtmChannelType channelType
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
Basic usage
var (status,response) = await rtmClient.getStorage.getChannelMetadata(
"myChannel",
RtmChannelType.message,
)
if (status.error == true) {
print(status);
} else {
print(response);
}Returns
Calling this method returns a Future<(RtmStatus, GetChannelMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call is successful, the second item of the tuple returns a
GetChannelMetadataResulttype data, defined as follows:
class GetChannelMetadataResult {
final String channelName; // The channel being operated on
final RtmChannelType channelType; // The type of the channel being operated on
final Metadata data; // Metadata data
}removeChannelMetadata
Description
The removeChannelMetadata method can remove channel metadata or metadata items.
When removing channel metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:
- The default value of the revision property is
-1, indicating that this method call does not perform any CAS verification. If the channel metadata or metadata item already exists, the SDK removes it. If the channel metadata or metadata item does not exist, the SDK returns an error code. - If the revision property is a positive integer, this method call performs the CAS verification. If the channel metadata or metadata item already exists, the SDK removes the corresponding value after the version number verification succeeds. If the channel metadata or metadata item does not exist, the SDK returns the error code.
After successfully removing channel metadata or metadata items, users who subscribe to the channel and enable event listeners can receive the channel type of the storage event notification. See Event listeners.
Method
You can call the removeChannelMetadata method as follows:
Future<(RtmStatus, RemoveChannelMetadataResult?)> removeChannelMetadata(
String channelName,
RtmChannelType channelType,
{
int majorRevision = -1,
List<MetadataItem> metadata = const [],
bool recordTs = false,
bool recordUserId = false,
String lockName = ''
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
majorRevision | int | Optional | -1 | Version control switch: - -1: Disable version verification.- > 0: Enable version verification, only execute the operation if the target version number matches this value. |
metadata | List<MetadataItem> | Optional | - | Metadata item. See MetadataItem. |
lockName | String | Optional | '' | Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations. |
recordTs | bool | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | bool | Optional | false | Whether to record the user ID of the editor. |
Basic usage
var item1 = MetadataItem(
key: 'Apple',
revision: 174298200
);
var item2 = MetadataItem(
key: 'Banana',
revision: 174298100
);
var metadata = [item1,item2];
var (status,response) = await rtmClient.getStorage.removeChannelMetadata(
"myChannel",
RtmChannelType.message,
metadata,
majorRevision: 174298222,
recordTs: true,
recordUserId: true,
lockName: "myLock"
);
if (status.error == true) {
print(status);
} else {
print(response);
}Returns
Calling this method returns a Future<(RtmStatus, RemoveChannelMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call is successful, the second item of the tuple returns a
RemoveChannelMetadataResulttype data, defined as follows:
class RemoveChannelMetadataResult {
final String channelName; // The channel being operated on
final RtmChannelType channelType; // The type of the channel being operated on
}updateChannelMetadata
Description
The updateChannelMetadata method can update existing channel metadata. Each time you call this method, you can update one channel metadata or a channel metadata item.
After successfully updating channel metadata, users who subscribe to the channel and enable event listeners can receive the channel type of the storage event notification. See Event listeners.
Information
You cannot use this method to update metadata items which do not exist.
Method
You can call the updateChannelMetadata method as follows:
Future<(RtmStatus, UpdateChannelMetadataResult?)> updateChannelMetadata(
String channelName,
RtmChannelType channelType,
List<MetadataItem> metadata = const [],
{
int majorRevision = -1,
bool recordTs = false,
bool recordUserId = false,
String lockName = ''
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
metadata | List<MetadataItem> | Optional | - | Metadata item. See MetadataItem. |
majorRevision | int | Optional | -1 | Version control switch: - -1: Disable version verification.- > 0: Enable version verification, only execute the operation if the target version number matches this value. |
recordTs | bool | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | bool | Optional | false | Whether to record the user ID of the editor. |
lockName | String | Optional | '' | Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations. |
Basic usage
var item1 = MetadataItem(
key: 'Apple',
value: '330',
revision: 174298200
);
var item2 = MetadataItem(
key: 'Banana',
value: '480',
revision: 174298100
);
var metadata = [item1,item2];
var (status,response) = await rtmClient.getStorage.updateChannelMetadata(
"myChannel",
RtmChannelType.message,
metadata,
majorRevision: 174298222,
recordTs: true,
recordUserId: true,
lockName: "myLock"
);
if (status.error == true) {
print(status);
} else {
print(response);
}Returns
Calling this method returns a Future<(RtmStatus, UpdateChannelMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call is successful, the second item of the tuple returns a
UpdateChannelMetadataResulttype data, defined as follows:
class UpdateChannelMetadataResult {
final String channelName; // The channel being operated on
final RtmChannelType channelType; // The type of the channel being operated on
}setUserMetadata
Description
The setUserMetadata method can set metadata for a user. If you call this method multiple times, the SDK retrieves the key of the metadata items in turn and apply settings according to the following rules:
- If you set metadata with different
key, the SDK adds each set of metadata in sequence according to the order of the method calls. - If you set metadata with the same
key, thevalueof the last setting overwrites the previous one.
After successfully setting user metadata, users who subscribe to the user and enable event listeners can receive the user type of the storage event notification. See Event listeners.
User metadata also introduces the version control logic CAS (Compare And Set). This method provides two independent version control fields, and you can set one or more of them according to your actual business use-case:
- Enable version number verification for the entire set of channel metadata by setting the
majorRevisionproperty. - Enable version number verification for a single metadata item by setting the
revisionproperty in theMetadataItemclass.
When setting user metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:
- The default value of the revision property is
-1, indicating that this method call does not perform any CAS verification. If the user metadata or metadata item already exists, the latest value overwrites the previous one. If the user metadata or metadata item does not exist, the SDK creates it. - If the revision property is a positive integer, this method call performs the CAS verification. If the user metadata or metadata item already exists, the SDK updates the corresponding value after the version number verification succeeds. If the user metadata or metadata item does not exist, the SDK returns the error code.
After successfully setting user metadata, users who subscribe to the user and enable event listeners can receive the user type of the storage event notification. See Event listeners.
Method
You can call the setUserMetadata method as follows:
Future<(RtmStatus, SetUserMetadataResult?)> setUserMetadata(
String userId,
List<MetadataItem> metadata,
{
int majorRevision = -1,
bool recordTs = false,
bool recordUserId = false
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | String | Required | - | User ID. |
metadata | List<MetadataItem> | Required | - | Metadata item. See MetadataItem. |
majorRevision | int | Optional | -1 | The version control switch: - -1: Disable the version verification.- > 0: Enable the version verification. The operation can only be performed if the target version number matches this value. |
recordTs | bool | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | bool | Optional | false | Whether to record the user ID of the editor. |
Basic usage
var item1 = MetadataItem(
key: 'Name',
value: 'Tony',
revision: 174298200
);
var item2 = MetadataItem(
key: 'Mute',
value: 'true',
revision: 174298100
);
var metadata = [item1,item2];
var (status,response) = await rtmClient.getStorage.setUserMetadata(
"Tony",
metadata,
majorRevision: 174298222,
recordTs: true,
recordUserId: true
);
if (status.error == true) {
print(status);
} else {
print(response);
}Return
This method returns a Future<(RtmStatus, SetUserMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
SetUserMetadataResultobject, defined as follows:
class SetUserMetadataResult {
final String userId; // The user ID of the current operation
}getUserMetadata
Description
The getUserMetadata method can get the metadata and metadata item for the specified user.
Method
You can call the getUserMetadata method as follows:
Future<(RtmStatus, GetUserMetadataResult?)> getUserMetadata(String userId);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | String | Required | - | User ID. |
Basic usage
var (status,response) = await rtmClient.getStorage.getUserMetadata( "Tony" );
if (status.error == true) {
print(status);
} else {
print(response);
}Return
This method returns a Future<(RtmStatus, GetUserMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
GetUserMetadataResultobject, defined as follows:
class GetUserMetadataResult {
final String userId; // The user ID of the current operation
final Metadata data; // User metadata
}removeUserMetadata
Description
The removeUserMetadata method can remove user metadata or metadata items.
After successfully removing user metadata, users who subscribe to the user and enable event listeners can receive the user type of the storage event notification. See Event listeners.
Method
You can call the removeUserMetadata method as follows:
Future<(RtmStatus, RemoveUserMetadataResult?)> removeUserMetadata(
String userId,
{
int majorRevision = -1,
List<MetadataItem> metadata = const [],
bool recordTs = false,
bool recordUserId = false
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | String | Required | - | User ID. |
majorRevision | int | Optional | -1 | The version control switch: - -1: Disable the version verification.- > 0: Enable the version verification. The operation can only be performed if the target version number matches this value. |
metadata | List<MetadataItem> | Optional | const [] | Metadata item. See MetadataItem. |
recordTs | bool | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | bool | Optional | false | Whether to record the user ID of the editor. |
Basic usage
var item1 = MetadataItem(
key: 'Name',
revision: 174298200
);
var item2 = MetadataItem(
key: 'Mute',
revision: 174298100
);
var metadata = [item1,item2];
var (status,response) = await rtmClient.getStorage.removeUserMetadata(
"Tony",
metadata: metadata
majorRevision: 174298222,
recordTs: true,
recordUserId: true
);
if (status.error == true) {
print(status);
} else {
print(response);
}Return
This method returns a Future<(RtmStatus, RemoveUserMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
RemoveUserMetadataResultobject, defined as follows:
class RemoveUserMetadataResult {
final String userId; // The user ID of the current operation
}updateUserMetadata
Description
The updateUserMetadata method can update existing user metadata.
After successfully updating channel metadata, users who subscribe to the user and enable event listeners can receive the user type of the storage event notification. See Event listeners.
Information
You cannot use this method to update metadata items which do not exist.
Method
You can call the updateUserMetadata method as follows:
Future<(RtmStatus, UpdateUserMetadataResult?)> updateUserMetadata(
String userId,
List<MetadataItem> metadata,
{
int majorRevision = -1,
bool recordTs = false,
bool recordUserId = false
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | String | Required | - | User ID. |
metadata | List<MetadataItem> | Required | - | Metadata item. See MetadataItem. |
majorRevision | int | Optional | -1 | The version control switch: - -1: Disable the version verification.- > 0: Enable the version verification. The operation can only be performed if the target version number matches this value. |
recordTs | bool | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | bool | Optional | false | Whether to record the user ID of the editor. |
Basic usage
var item1 = MetadataItem(
key: 'Name',
value: 'Sara',
revision: 174298200
);
var item2 = MetadataItem(
key: 'Mute',
value: 'false',
revision: 174298100
);
var metadata = [item1,item2];
var (status,response) = await rtmClient.getStorage.updateUserMetadata(
"Sara",
metadata,
majorRevision: 174298222,
recordTs: true,
recordUserId: true
);
if (status.error == true) {
print(status);
} else {
print(response);
}Return
This method returns a Future<(RtmStatus, UpdateUserMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
UpdateUserMetadataResultobject, defined as follows:
class UpdateUserMetadataResult {
final String userId; // The user ID of the current operation
}subscribeUserMetadata
Description
The subscribeUserMetadata method can subscribe to metadata for a specified user.
After successfully subscribing to the user metadata, you can receive the user type of the storage event notification when the metadata for that user changes. See Event listeners.
Method
You can call the subscribeUserMetadata method as follows:
Future<(RtmStatus, SubscribeUserMetadataResult?)> subscribeUserMetadata(String userId);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | String | Required | - | User ID. |
Basic usage
var (status,response) = await rtmClient.getStorage.subscribeUserMetadata( "Sara");
if (status.error == true) {
print(status);
} else {
print(response);
}Return
This method returns a Future<(RtmStatus, SubscribeUserMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
SubscribeUserMetadataResultobject, defined as follows:
class SubscribeUserMetadataResult {
final String userId; // The user ID of the current operation
}unsubscribeUserMetadata
Description
If you do not need to receive notifications of changes to a user metadata, call the unsubscribeUserMetadata method to unsubscribe.
Method
You can call the unsubscribeUserMetadata method as follows:
Future<(RtmStatus, UnsubscribeUserMetadataResult?)> unsubscribeUserMetadata(String userId);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | String | Required | - | User ID. |
Basic usage
var (status,response) = await rtmClient.getStorage.unsubscribeUserMetadata( "Sara");
if (status.error == true) {
print(status);
} else {
print(response);
}Return
This method returns a Future<(RtmStatus, UnsubscribeUserMetadataResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
UnsubscribeUserMetadataResultobject, defined as follows:
class UnsubscribeUserMetadataResult {
final String userId; // The user ID of the current operation
}MetadataItem
Use the MetadataItem data type to set and manage metadata items, containing the following properties:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
key | String | Optional | - | Key. |
value | String | Optional | - | Value. |
authorUserId | String | Optional | - | The user ID of the editor. This value is read-only and does not support writing. |
revision | int | Optional | -1 | - Returns the real version number in read operations. - Serves as a version control switch in write operations: - -1: Disable the version verification. - > 0: Enable version verification, only perform the operation if the target version number matches this value. |
updateTs | int | Optional | 0 | Update timestamp. This value is read-only and does not support writing. |
Lock
A critical resource can only be used by one process at a time. If a critical resource is shared between different processes, each process needs to adopt a mutually exclusive method to prevent mutual interference. Signaling provides a full set of lock solutions. By controlling different processes in a distributed system, you can solve the competition problem when users access shared resources.
Information
The client is able to set, remove, and revoke locks. We recommend that you control the permissions of these operations on the client side based on your business needs.
RtmLock Lock instance
setLock
Description
You need to configure the lock name, time to live (TTL), and other parameters by calling the setLock method. If the configuration succeeds, all users in the channel receive the lock event notifications of the lockSet type. For details, see Event Listeners.
Method
You can call the setLock method as follows:
Future<(RtmStatus, SetLockResult?)> setLock(
String channelName,
RtmChannelType channelType,
String lockName,
{
int? ttl = 10
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
lockName | String | Required | - | Lock name. |
ttl | int | Optional | 10 | The expiration time of the lock. The value is in seconds, ranging from [10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the lock event receive the lockReleased event. |
Basic usage
var (status,response) =
await rtmClient.getLock.setLock( "myChannel", RtmChannelType.message, "myLock", ttl:15);
if (status.error == true) {
print(status);
} else {
print(response);
}Return
Calling this method returns a Future<(RtmStatus, SetLockResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
SetLockResultobject, defined as follows:
class SetLockResult {
final String channelName; // Channel name
final RtmChannelType channelType; // Channel type
final String lockName; // Lock name
}acquireLock
Description
After successfully configuring a lock, you can call the acquireLock method on the client to acquire the right to own the lock. When you acquire the lock, other users in the channel receive the lockAcquired type of the lock event. For details, see Event Listeners.
Method
You can call the acquireLock method as follows:
Future<(RtmStatus, AcquireLockResult?)> acquireLock(
String channelName,
RtmChannelType channelType,
String lockName,
{
bool retry = false
}
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
lockName | String | Required | - | Lock name. |
retry | bool | Optional | false | If the lock acquisition fails, whether to retry until the acquisition succeeds or the user leaves the channel. |
Basic usage
var (status,response) =
await rtmClient.getLock.acquireLock("myChannel", RtmChannelType.message, "myLock", retry:true);
if (status.error == true) {
print(status);
} else {
print(response);
}Return
Calling this method returns a Future<(RtmStatus, AcquireLockResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns an
AcquireLockResultobject, defined as follows:
class AcquireLockResult {
final String channelName; // Channel name
final RtmChannelType channelType; // Channel type
final String lockName; // Lock name
final String errorDetails; // Error details
}releaseLock
Description
When a user no longer needs to own a lock, the user can call the releaseLock method on the client side to release the lock. After successful release the lock, other users in the channel receive the lockReleased type of the lock event. See Event Listeners.
At this time, if other users want to acquire the lock, they can call the acquireLock method on the client side to compete. New users acquiring locks have the same contention priority as the users who set the retry property to automatically retry to acquire locks.
Method
You can call the releaseLock method as follows:
Future<(RtmStatus, ReleaseLockResult?)> releaseLock(
String channelName,
RtmChannelType channelType,
String lockName
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
lockName | String | Required | - | Lock name. |
Basic usage
var (status,response) =
await rtmClient.getLock.releaseLock("myChannel", RtmChannelType.message, "myLock");
if (status.error == true) {
print(status);
} else {
print(response);
}Return
Calling this method returns a Future<(RtmStatus, ReleaseLockResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
ReleaseLockResultobject, defined as follows:
class ReleaseLockResult {
final String channelName; // Channel name
final RtmChannelType channelType; // Channel type
final String lockName; // Lock name
}revokeLock
Description
When the lock is occupied, to ensure that your business is not affected, you may need to revoke the lock and give other users a chance to obtain it. Revoke the occupied lock by calling revokeLock. When the lock is revoked, all users in the channel receive the lockReleased type of the lock event. See Event Listeners.
At this time, if other users want to acquire the lock, they can call the acquireLock method on the client side to compete. New users acquiring locks have the same contention priority as the users who set the retry property to automatically retry to acquire locks.
Method
You can call the revokeLock method as follows:
Future<(RtmStatus, RevokeLockResult?)> revokeLock(
String channelName,
RtmChannelType channelType,
String lockName,
String owner
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
lockName | String | Required | - | Lock name. |
owner | String | Required | - | The ID of the user who has a lock. |
Basic usage
var (status,response) = await rtmClient.getLock.revokeLock("myChannel", RtmChannelType.message, "myLock", "Tony");
if (status.error == true) {
print(status);
} else {
print(response);
}Return
Calling this method returns a Future<(RtmStatus, RevokeLockResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
RevokeLockResultobject, defined as follows:
class RevokeLockResult {
final String channelName; // Channel name
final RtmChannelType channelType; // Channel type
final String lockName; // Lock name
}Description
If you want to query the lock information such as lock total number, lock name, lock user, and time to live, you can call the `` method on the client.
Method
You can call the `` method as follows:
Future<(RtmStatus, GetLocksResult?)> getLocks(
String channelName,
RtmChannelType channelType
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
Basic usage
var (status,response) =
await rtmClient.getLock.getLocks("myChannel", RtmChannelType.message);
if (status.error == true) {
print(status);
} else {
print(response);
}Return
Calling this method returns a Future<(RtmStatus, GetLocksResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
GetLocksResultobject, defined as follows:
class GetLocksResult {
final String channelName; // Channel name
final RtmChannelType channelType; // Channel type
final List<LockDetail> lockDetailList; // Lock details
final int count; // Lock count
}removeLock
Description
If you no longer need a lock, you can call the removeLock method to remove the lock. After successfully removing the lock, all users in the channel receive the lockRemoved type of lock event notification. See Event Listeners.
Method
You can call the removeLock method as follows:
Future<(RtmStatus, RemoveLockResult?)> removeLock(
String channelName,
RtmChannelType channelType,
String lockName
);| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | String | Required | - | Channel name. |
channelType | RtmChannelType | Required | - | Channel types. See RtmChannelType. |
lockName | String | Required | - | Lock name. |
Basic usage
var (status,response) =
await rtmClient.getLock.removeLock("myChannel", RtmChannelType.message, "myLock");
if (status.error == true) {
print(status);
} else {
print(response);
}Return
Calling this method returns a Future<(RtmStatus, RemoveLockResult?)> tuple data.
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
- If the method call succeeds, the second item of the tuple returns a
RemoveLockResultobject, defined as follows:
class RemoveLockResult {
final String channelName; // Channel name
final RtmChannelType channelType; // Channel type
final String lockName; // Lock name
}Enumerated types
Enum
RtmAreaCode
The region for connection, which is the region where the server the SDK connects to is located.
| Value | Description |
|---|---|
cn | 0x00000001: Mainland China. |
na | 0x00000002: North America. |
eu | 0x00000004: Europe. |
asm | 0x00000008: Asia, excluding Mainland China. |
jp | 0x00000010: Japan. |
ind | 0x00000020: India. |
glob | 0xFFFFFFFF: Global. |
RtmChannelType
Channel types.
| Value | Description |
|---|---|
message | 1: Message channel. |
stream | 2: Stream channel. |
user | 3: User Channel. |
RtmConnectionChangeReason
Reasons causing the change of the connection state.
| Value | Description |
|---|---|
connecting | 0: The SDK is connecting with the server. |
joinSuccess | 1: The SDK has joined the channel successfully. |
interrupted | 2: The connection between the SDK and the server is interrupted. |
bannedByServer | 3: The connection between the SDK and the server is banned by the server. |
joinFailed | 4: The SDK fails to join the channel. When the SDK fails to join the channel for more than 20 minutes, this error occurs and the SDK stops reconnecting to the channel. |
leaveChannel | 5: The SDK has left the channel. |
invalidAppId | 6: The connection failed because the App ID is not valid. |
invalidChannelName | 7: The connection failed because the channel name is not valid. |
invalidToken | 8: The connection failed because the token is not valid. |
tokenExpired | 9: The connection failed because the token is expired. |
rejectedByServer | 10: The connection is rejected by server. |
settingProxyServer | 11: The connection state changed to reconnecting because the SDK has set a proxy server. |
renewToken | 12: The connection state changed because the token is renewed. |
clientIpAddressChanged | 13: The IP address of the client has changed, possibly because the network type, IP address, or port has been changed. |
keepAliveTimeout | 14: Timeout for the keep-alive of the connection between the SDK and the server. The connection state changes to reconnecting. |
rejoinSuccess | 15: The user has rejoined the channel successfully. |
lost | 16: The connection between the SDK and the server is lost. |
echoTest | 17: The connection state changes due to the echo test. |
clientIpAddressChangedByUser | 18: The local IP address was changed by the user. The connection state changes to reconnecting. |
sameUidLogin | 19: The user joined the same channel from different devices with the same UID. |
tooManyBroadcasters | 20: The number of hosts in the channel has reached the upper limit. |
licenseValidationFailure | 21: The license validation failed. |
certificationVerifyFailure | 22: The server certificate validation failed. |
streamChannelNotAvailable | 23: The stream channel does not exist. |
inconsistentAppid | 24: The App ID does not match the token. |
loginSuccess | 10001: The SDK logs in to the Signaling system. |
logout | 10002: The SDK logs out from the Signaling system. |
presenceNotReady | 10003: Presence service is not ready. You need to call the login method again to log in to the Signaling system and re-execute all operations on the SDK. |
RtmConnectionState
SDK connection states.
| Value | Description |
|---|---|
disconnected | 1: The SDK has disconnected with the server. |
connecting | 2: The SDK is connecting with the server. |
connected | 3: The SDK has connected with the server. |
reconnecting | 4: The connection is lost. The SDK is reconnecting with the server. |
failed | 5: The SDK failed to connect with the server. |
RtmLinkStateChangeReason
| Value | Description |
|---|---|
unknown | 0: Unknown reason. |
login | 1: Logging in. |
loginSuccess | 2: Login successful. |
loginTimeout | 3: Login timeout. |
loginNotAuthorized | 4: Login not authorized. |
loginRejected | 5: Login rejected. |
relogin | 6: Re-login. |
logout | 7: Logout. |
autoReconnect | 8: Auto-reconnect. |
reconnectTimeout | 9: Reconnect timeout. |
reconnectSuccess | 10: Reconnect successful. |
join | 11: Joining a channel. |
joinSuccess | 12: Join channel successful. |
joinFailed | 13: Join channel failed. |
rejoin | 14: Re-join a channel. |
leave | 15: Leave a channel. |
invalidToken | 16: Invalid token. |
tokenExpired | 17: Token expired. |
inconsistentAppId | 18: Inconsistent app ID. |
invalidChannelName | 19: Invalid channel name. |
invalidUserId | 20: Invalid user ID. |
notInitialized | 21: SDK not initialized. |
rtmServiceNotConnected | 22: RTM service not connected. |
channelInstanceExceedLimitation | 23: Channel instance exceeds the limit. |
operationRateExceedLimitation | 24: Operation frequency exceeds the limit. |
channelInErrorState | 25: Channel in error state. |
presenceNotConnected | 26: Presence service not connected. |
sameUidLogin | 27: Login with the same user ID. |
kickedOutByServer | 28: Kicked out by the server. |
keepAliveTimeout | 29: Keepalive timeout. |
connectionError | 30: Connection error. |
presenceNotReady | 31: Presence service not ready. |
networkChange | 32: Network changed. |
serviceNotSupported | 33: Service not supported. |
streamChannelNotAvailable | 34: Stream Channel not available. |
storageNotAvailable | 35: Storage service not available. |
lockNotAvailable | 36: Lock service not available. |
loginTooFrequent | 37: The login operation is too frequent. |
RtmEncryptionMode
Encryption mode.
| Value | Description |
|---|---|
none | 0: No encryption. |
aes128Gcm | 1: AES-128-GCM mode. |
aes256Gcm | 2: AES-256-GCM mode. |
RtmLockEventType
Lock event type.
| Value | Description |
|---|---|
snapshot | 1: The snapshot of the lock when the user joined the channel. |
lockSet | 2: The lock is set. |
lockRemoved | 3: The lock is removed. |
lockAcquired | 4: The lock is acquired. |
lockReleased | 5: The lock is released. |
lockExpired | 6: The lock expired. |
RtmLogLevel
Log output levels.
| Value | Description |
|---|---|
none | 0x0000: No log. |
info | 0x0001: Output the log at the FATAL, ERROR, WARN, or INFO level. We recommend you set to this value. |
warn | 0x0002: Output the log at the FATAL, ERROR, WARN level. |
error | 0x0004: Output the log at the FATAL, ERROR level. |
fatal | 0x0008: Output the log at the FATAL level. |
RtmMessagePriority
Message priority.
| Value | Description |
|---|---|
highest | 0: Highest. |
high | 1: High. |
normal | 4: Normal. |
low | 8: Low. |
RtmMessageQos
QoS guarantee when sending topic messages.
| Value | Description |
|---|---|
unordered | 0: Message data is not guaranteed to arrive in order. |
ordered | 1: Message data arrives in order. |
RtmMessageType
Message Type.
| Enum Value | Description |
|---|---|
binary | 0: Binary type. |
string | 1: String type. |
RtmPresenceEventType
Presence event type.
| Value | Description |
|---|---|
snapshot | 1: The snapshot of the presence when the user joined the channel. |
interval | 2: When users in the channel reach the setting value, the event notifications are sent at intervals rather than in real time. |
remoteJoinChannel | 3: A remote user joined the channel. |
remoteLeaveChannel | 4: A remote user left the channel. |
remoteTimeout | 5: A remote user's connection timed out. |
remoteStateChanged | 6: A remote user's temporary state changed. |
errorOutOfService | 7: The user did not enable presence when joining the channel. |
RtmLinkOperation
Operation type.
| Value | Description |
|---|---|
login | 0: The user logins to the Signaling system. |
logout | 1: The user logouts of the Signaling system. |
join | 2: The user joins in a stream channel. |
leave | 3: The user leaves a stream channel. |
serverReject | 4: The Signaling server reject the connection. |
autoReconnect | 5: The SDK is automatically reconnecting to the Signaling server. |
reconnected | 6: The SDK is reconnected to the Signaling server. |
heartbeatLost | 7: The Signaling server does not receive the heartbeat packet within the specified timeout period. |
serverTimeout | 8: The Signaling server has timed out. |
networkChange | 9: The network status changes. |
RtmLinkState
Link state type.
| Value | Description |
|---|---|
idle | 0: The init state. |
connecting | 1: Connecting. |
connected | 2: Connected. |
disconnected | 3: Disconnected. |
suspended | 4: Suspended. |
failed | 5: Failed. |
RtmProtocolType
Protocol type.
| Value | Description |
|---|---|
tcpUdp | 0: Both TCP and UDP protocols. |
tcpOnly | 1: Only TCP protocol. |
RtmServiceType
Service type
| Value | Description |
|---|---|
message | The foundational services comprise the message channel, user channel, presence, storage, and lock services. |
stream | The stream channel service. |
Information
To fully utilize all services offered by Signaling, you can employ bitwise operations to simultaneously configure two service types.
RtmProxyType
Proxy type.
| Value | Description |
|---|---|
none | 0: Do not enable the proxy. |
http | 1: Enable the proxy for the HTTP protocol. |
cloudTcp | 2: Enable the cloud proxy for the TCP protocol. |
RtmStorageEventType
Storage event type.
| Value | Description |
|---|---|
snapshot | 1: When a user subscribes to channel metadata or user etadata for the first time, or joins a channel, the local user receives notifications of this type of event. |
set | 2: Occurs when calling setChannelMetadata or setUserMetadata. Caution: This event only occurs in incremental data update mode. |
update | 3: Occurs when calling methods to set, update, or delete the channel metadata or user metadata. |
remove | 4: Occurs when calling removeChannelMetadata or removeUserMetadata. Caution: This event only occurs in incremental data update mode. |
RtmStorageType
Storage type.
| Value | Description |
|---|---|
user | 1: User metadata event. |
channel | 2: Channel metadata event. |
RtmTopicEventType
Topic event type.
| Value | Description |
|---|---|
snapshot | 1: The snapshot of the topic when the user joined the channel. |
remoteJoinTopic | 2: A remote user joined the channel. |
remoteLeaveTopic | 3: A remote user left the channel. |
Troubleshooting
Refer to the following information for troubleshooting API calls.
ErrorInfo
Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:
class RtmStatus {
bool error; // Indicates whether there was an error in this operation.
String errorCode; // The error code for this operation.
String operation; // The operation.
String reason; // A brief description of the error reason for this operation.
}You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.
Error codes table
Refer to the following error codes table to identify and troubleshoot the problem:
| Error code | Error description | Cause and solution |
|---|---|---|
0 | ok | Correct call |
-10001 | notInitialized | The SDK is not initialized. Please initialize the RtmClient instance by calling the createAgoraRtmClient method before performing other operations. |
-10002 | notLogin | The user called the API without logging in to Signaling, disconnected due to timeout, or actively logged out. Please log in to Signaling first. |
-10003 | invalidAppId | Invalid App ID: - Check that the App ID is correct. - Ensure that Signaling has been activated for the App ID. |
-10005 | invalidToken | Invalid Token: - The token is invalid, check whether the Token Provider generates a valid Signaling Token. |
-10006 | invalidUserId | Invalid User ID: - Check if user ID is empty. - Check if the user ID contains illegal characters. |
-10007 | initServiceFailed | SDK initialization failed. Please reinitialize by calling the createAgoraRtmClient method. |
-10008 | invalidChannelName | Invalid channel name: - Check if the channel name is empty. - Check if the channel name contains illegal characters. |
-10009 | tokenExpired | Token expired. Call renewToken to reacquire the Token. |
-10010 | loginNoServerResources | Server resources are limited. It is recommended to log in again. |
-10011 | loginTimeout | Login timeout. Check whether the current network is stable and switch to a stable network environment. |
-10012 | loginRejected | SDK login rejected by the server: - Check tha Signaling is activated on your App ID. - Check if the token or userId is banned. |
-10013 | loginAborted | SDK login interrupted due to unknown problem: - Check that the current network is stable and switch to a stable network environment. - The current userId is logged in. |
-10014 | invalidParameter | Invalid parameter. Please check if the parameters you provided are correct. |
-10015 | loginNotAuthorized | No RTM service permissions. Check that the console opens Signaling services. |
-10016 | inconsistentAppid | Inconsistent App ID. Please check whether the App ID used for initialization, login, and joining a channel are consistent. |
-10017 | duplicateOperation | Duplicate operation. |
-10018 | instanceAlreadyReleased | Repeat rtm instantiation or RTMStreamChannel instantiation. |
-10019 | invalidChannelType | Invalid channel type. The SDK only supports the following channel types. Please use the correct value: - message: Message Channel - stream: Stream Channel - user: User Channel |
-10020 | invalidEncryptionParameter | Message encryption parameters are invalid. - Check that the encryption key generated is a String. - Check that the generated encryption salt is Uint8Array type and that the length is 32 bytes. - Check that the encryption method matches the encryption key and the encryption salt. |
-10021 | operationRateExceedLimitation | Channel metadata or User Metadata -related API call frequency is exceeding the limit. Please control the call frequency within 10/second. |
-10022 | serviceNotSupported | The service type is not supported. Check whether the service type you set in RtmServiceType is correct. This error code is only applicable to the private deployment function. |
-10023 | loginCanceled | The login operation has been canceled. Possible reasons are as follows: - After calling the login method, if you call the method again before receiving the call result, the previous call operation will be canceled and the SDK will execute the next call. - Calling the logout method to log out before successfully logging in. |
-10024 | invalidPrivateConfig | The private deployment parameter settings are invalid. Please check whether the service type and server address you set in RtmPrivateConfig are valid. |
-10025 | notConnected | Not connected to the Signaling server. |
-10026 | renewTokenTimeout | Token renewal timed out. |
-11001 | channelNotJoined | The user has not joined the channel: - The user is not online, offline or has not joined the channel - Check for typos in userId. |
-11002 | channelNotSubscribed | The user has not subscribed to the channel: - The user is not online, offline or has not joined the channel - Check for typos in userId. |
-11003 | channelExceedTopicUserLimitation | The number of subscribers to this topic exceeds the limit. |
-11004 | channelInReuse | In co-channel mode, RTM released the Stream Channel. |
-11005 | channelInstanceExceedLimitation | The number of created or subscribed channels exceeds the limit. See API usage limits for details. |
-11006 | channelInErrorState | Channel is not available. Please recreate the Stream Channel or resubscribe to the Message Channel. |
-11007 | channelJoinFailed | Failed to join this channel: - Check if the number of joined channels exceeds the limit. - Check if the channel name is illegal. - Check if the network is disconnected. |
-11008 | channelInvalidTopicName | Invalid topic name: - Check whether the topic name contains illegal characters. - Check if the topic name is empty. |
-11009 | channelInvalidMessage | Invalid message. Check whether the message type is legal, Signaling only supports string, Uint8Array type messages. |
-11010 | channelMessageLengthExceedLimitation | Message length exceeded limit. Check if the message payload size exceeds the limit: - Message Channel single message package limit is 32 KB. - Stream Channel single message package limit is 1 KB. |
-11011 | channelInvalidUserList | Invalid user list: - Check if the user list is empty. - Check if the user list contains invalid entries. |
-11012 | channelNotAvailable | Invalid user list: - Check if the user list is empty - Check if the user list contains illegal items. |
-11013 | channelTopicNotSubscribed | The topic is not subscribed. |
-11014 | channelExceedTopicLimitation | The number of topics exceeds the limit. |
-11015 | channelJoinTopicFailed | Failed to join this topic. Check whether the number of added topics exceeds the limit. |
-11016 | channelTopicNotJoined | The topic has not been joined. To send a message, you need to join the Topic first. |
-11017 | channelTopicNotExist | The topic does not exist. Check that the topic name is correct. |
-11018 | channelInvalidTopicMeta | The meta parameters in the topic are invalid. Check if the meta parameter exceeds 256 bytes. |
-11019 | channelSubscribeTimeout | Channel subscription timed out. Check for broken connections. |
-11020 | channelSubscribeTooFrequent | The channel subscription operation is too frequent. Make sure that the subscription operation of the same channel within a 5 seconds interval does not exceed 2 attempts. |
-11021 | channelSubscribeFailed | Channel subscription failed. Check if the number of subscribed channels exceeds the limit. |
-11022 | channelUnsubscribeFailed | Failed to unsubscribe from the channel. Check if the connection is disconnected. |
-11023 | channelEncryptMessageFailed | Message encryption failed: - Check that the cipherKey is valid. - Check that the salt is valid. - Check if encryptionMode mode matches the cipherKey and salt. |
-11024 | channelPublishMessageFailed | Message publishing failed. Check for broken connections. |
-11026 | channelPublishMessageTimeout | Message publishing timed out. Check for broken connections. |
-11027 | channelNotConnected | The SDK is disconnected from the Signaling server. Please log in again. |
-11028 | channelLeaveFailed | Failed to leave the channel. Check for broken connections. |
-11029 | channelCustomTypeLengthOverflow | Custom type length overflow. The length of the customType field must to be within 32 characters. |
-11030 | channelInvalidCustomType | customType field is invalid. Check the customType field for illegal characters. |
-11031 | channelUnsupportedMessageType | Message type is not supported. |
-11032 | channelPresenceNotReady | Presence service is not ready. Please rejoin the Stream Channel or resubscribe to the Message Channel. |
-11033 | channelReceiverOffline | When sending a user message, the remote user is offline: - Check if the user ID set when calling the method is correct. - Check if the remote user is logged in and online. |
-11034 | channelJoinCanceled | The join channel operation has been canceled. After calling the joinTopic method, if you call the method again before receiving the call result, the previous call operation will be canceled and the SDK will execute the next call. |
-12001 | storageOperationFailed | Storage operation failed. |
-12002 | storageMetadataItemExceedLimitation | The number of Storage Metadata Items exceeds the limit. |
-12003 | storageInvalidMetadataItem | Invalid Metadata Item. |
-12004 | storageInvalidArgument | Invalid argument. |
-12005 | storageInvalidRevision | Invalid Revision parameter. |
-12006 | storageMetadataLengthOverflow | Metadata overflows. |
-12007 | storageInvalidLockName | Invalid Lock name. |
-12008 | storageLockNotAcquired | The Lock was not acquired. |
-12009 | storageInvalidKey | Invalid Metadata key. |
-12010 | storageInvalidValue | Invalid metadata value. |
-12011 | storageKeyLengthOverflow | Metadata key length overflow. |
-12012 | storageValueLengthOverflow | Metadata value length overflow. |
-12013 | storageDuplicateKey | Duplicate Metadata Item key. |
-12014 | storageOutdatedRevision | Outdated Revision parameter. |
-12015 | storageNotSubscribe | This channel is not subscribed. |
-12016 | storageInvalidMetadataInstance | Metadata instance does not exist. Please create a Metadata instance. |
-12017 | storageSubscribeUserExceedLimitation | The number of subscribers exceeds the limit. |
-12018 | storageOperationTimeout | Storage operation timed out. |
-12019 | storageNotAvailable | The Storage service is not available. |
-13001 | presenceNotConnected | The user is not connected to the system. |
-13002 | presenceNotWritable | Presence service is unavailable. |
-13003 | presenceInvalidArgument | Invalid argument. |
-13004 | presenceCachedTooManyStates | The temporary user state cached before joining the channel exceeds the limit. See API usage limits for details. |
-13005 | presenceStateCountOverflow | The number of temporary user state key/value pairs exceeds the limit. See API usage limits for details. |
-13006 | presenceInvalidStateKey | Invalid state key. |
-13007 | presenceInvalidStateValue | Invalid state value. |
-13008 | presenceStateKeySizeOverflow | Presence key length overflow. |
-13009 | presenceStateValueSizeOverflow | Presence value overflow |
-13010 | presenceStateDuplicateKey | Repeated state key. |
-13011 | presenceUserNotExist | The user does not exist. |
-13012 | presenceOperationTimeout | Presence operation timed out. |
-13013 | presenceOperationFailed | Presence operation failed. |
-14001 | lockOperationFailed | Lock operation failed. |
-14002 | lockOperationTimeout | Lock operation timed out. |
-14003 | lockOperationPerforming | Lock operation in progress. |
-14004 | lockAlreadyExist | Lock already exists. |
-14005 | lockInvalidName | Invalid Lock name. |
-14006 | lockNotAcquired | The Lock was not acquired. |
-14007 | lockAcquireFailed | Failed to acquire the Lock. |
-14008 | lockNotExist | The Lock does not exist. |
-14009 | lockNotAvailable | Lock service is not available. |
