Connection
Clients must successfully connect to the RC server before they can use the SDK's messaging features.
Upon receiving a connection request from a client, the RC server determines whether to allow the connection based on the user authentication token (Token parameter) carried in the request.
Prerequisites
- Obtain a Token via the server API User Registration (Get Token). The RC client SDK does not provide a method to obtain Tokens. Applications should call their own server to retrieve the Token from the RC server.
- After obtaining the Token, the client can save it as needed for future connections. The storage location depends on the application's design. If the Token is still valid, there's no need to request a new one from RC.
- Token validity periods can be configured in the Console, with the default being permanent. Even if a new Token is generated, the old Token remains valid until it expires. If a Token expires, a new one must be obtained. If necessary, you can actively call the server API Invalidate Token.
- It is recommended that applications set up connection status monitoring before connecting.
- The SDK must be initialized.
Do not call the server API directly from the client to obtain a Token. Retrieving a Token requires the App Key and App Secret. If these credentials are stored on the client and the app is decompiled, the App Key and App Secret could be leaked. Therefore, always ensure Tokens are obtained from the application server.
Connecting to the Chat Server
Depending on your application's business requirements and design, decide the appropriate timing (login, registration, or another point to prevent users from being unable to access the main page) to initiate a connection request to the RC chat server.
Note the following:
- The
connect()method must be called after SDK initialization. Otherwise, callbacks may not be triggered. - The SDK has its own reconnection mechanism. There's no need to call
connect()multiple times within an application lifecycle, as this may trigger multiple callbacks or clear existing ones. - Call it once in the application's main process.
Interface (with Timeout Setting)
For a client user's first connection to the chat server, it's recommended to use the interface with a connection timeout (timeLimit) and set the timeout duration. In cases of poor network conditions leading to timeout, you can use the timeout error callback to notify users via UI, such as suggesting they retry when the network is stable.
Once connected successfully, the SDK's reconnection mechanism takes over and handles all reconnection attempts. If disconnected due to network issues, the SDK will continuously retry until successful, requiring no additional actions from you. Active disconnection by the application exits the reconnection mechanism (see Disconnect). For other scenarios, refer to Reconnection Mechanism and Mutual Kick.
For subsequent offline logins, set the timeLimit parameter to 0. This allows page navigation as soon as the database opens (onDatabaseOpened), prioritizing the display of local historical data while leaving the connection logic entirely to the SDK.
Interface
IMCenter.connect(token, timeLimit, connectCallback);
Parameters
| Parameter | Type | Description |
|---|---|---|
| token | String | Token obtained from the server. |
| timeLimit | int | Timeout duration in seconds. No reconnection attempts after timeout. Values ≤ 0 mean the SDK will keep trying until successful or a business error occurs. |
| connectCallback | ConnectCallback | Connection callback. See Connect Callback Methods below. |
timeLimitParameter Details:timeLimit≤ 0: The IM SDK will keep trying to connect until successful or a business error occurs (e.g., invalid Token).timeLimit> 0: The IM SDK will attempt to connect for up totimeLimitseconds. If unsuccessful within this period, it stops retrying and notifies via theonErrorcallback, requiring a manualconnect()call.
Example Code
public void connectIM(String token){
int timeLimit = 0;
IMCenter.connect("UserToken", timeLimit, new RongIMClient.ConnectCallback() {
@Override
public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus code) {
if(RongIMClient.DatabaseOpenStatus.DATABASE_OPEN_SUCCESS.equals(code)) {
//Local database opened, navigate to the conversation list page
} else {
//Database opening failed, show a toast notification.
}
}
@Override
public void onSuccess(String s) {
//Connection successful. If no page navigation occurred in onDatabaseOpened(), do it here.
}
@Override
public void onError(RongIMClient.ConnectionErrorCode errorCode) {
if(errorCode.equals(RongIMClient.ConnectionErrorCode.RC_CONN_TOKEN_EXPIRE)) {
//Request a new Token from the app server, then call connect() again with the new Token
} else if (errorCode.equals(RongIMClient.ConnectionErrorCode.RC_CONNECT_TIMEOUT)) {
//Connection timeout. Notify the user and suggest retrying when the network is stable.
} else {
//Handle other business error codes accordingly.
}
}
})
}
Interface (No Timeout Setting)
For users who have previously logged in successfully and connected to the RC chat server, this interface is recommended for subsequent offline logins.
Since these users already have historical data, there's no strict dependency on a successful connection. Page navigation can occur as soon as the database opens (onDatabaseOpened), displaying local historical data first. The connection logic is entirely managed by the SDK.
In poor network conditions, callbacks may take a long time or not occur at all.
After calling this interface, the SDK's reconnection mechanism takes over. It will continuously retry until successful, requiring no additional actions. Active disconnection by the application exits the reconnection mechanism (see Disconnect). For other scenarios, refer to Reconnection Mechanism and Mutual Kick.
Interface
IMCenter.getInstance().connect(token, connectCallback);
Parameters
| Parameter | Type | Description |
|---|---|---|
| token | String | User authentication Token obtained from the server |
| connectCallback | ConnectCallback | Connection callback. See Connect Callback Methods. |
Connect Callback Methods
The connectCallback provides three callback methods:
-
onDatabaseOpened(DatabaseOpenStatus code)Local database opening status callback. When
DATABASE_OPEN_SUCCESSis returned, the local database is open, allowing retrieval of local historical conversations and messages. This is useful for offline login scenarios. -
onSuccess(String userId)Connection success callback, returning the currently connected user ID.
-
onError(ConnectionErrorCode errorCode)Connection failure callback with corresponding error codes. Developers should handle different business scenarios based on Connection Status Codes.
Common errors include:
-
Calling
connect()before SDK initialization. -
Mismatched App Key between the client and server, causing
TOKEN_INCORRECTerrors.RC provides separate App Key/Secret pairs for production and development environments. Switching from testing to production may cause mismatches.
-
Expired Token. See Get Token.
-
Connection Status Codes
| Name | Value | Description |
|---|---|---|
| IPC_DISCONNECT | -2 | IPC process terminated unexpectedly. Possible causes: 1. System policies terminated or unbound the IPC process. The IM SDK handles reconnection automatically; no additional action is needed. 2. Missing libRongIMLib.so or libsqlite.so for the CPU architecture. Ensure the correct .so files are integrated. |
| RC_CONN_ID_REJECT | 31002 | Incorrect AppKey. Verify the AppKey used. |
| RC_CONN_TOKEN_INCORRECT | 31004 | Invalid Token. Ensure the AppKey used for client initialization matches the one used by your server to obtain the Token. |
| RC_CONN_NOT_AUTHRORIZED | 31005 | App verification failed (App verification is enabled but failed). |
| RC_CONN_APP_BLOCKED_OR_DELETED | 31008 | App is blocked or deleted. Check if the AppKey is blocked or deleted. |
| RC_CONN_USER_BLOCKED | 31009 | Connection failed, usually because the user is blocked. Check the Token and whether the corresponding UserId is blocked. |
| RC_CONN_TOKEN_EXPIRE | 31020 | Token expired. Typically occurs when a Token expiration period is set in the Console. Request a new Token from your server and reconnect with it. |
| RC_CLIENT_NOT_INIT | 33001 | SDK not initialized. Initialize the SDK before using any features. |
| RC_CONNECTION_EXIST | 34001 | Connection already exists or is reconnecting. |
| RC_CONNECT_TIMEOUT | 34006 | Internal SDK connection timeout. Occurs when using the timeout-enabled connect interface with a valid timeLimit.The SDK stops retrying; manually call connect() to reconnect. |
| UNKNOWN | -1 | Unknown error. |