Skip to main content

Connection

The RC IM SDK's messaging functionality becomes available only after the application client successfully connects to RC servers.

Upon receiving a connection request from the client, RC servers will verify whether to permit the connection based on the user authentication token (Token) carried in the request.

Prerequisites

  • Obtain a Token through the server-side API User Registration (Get Token). The RC client SDK does not provide Token retrieval methods. Applications should call their own server to obtain Tokens from RC servers.
    • After obtaining the Token, clients may store it as needed for future connections. The specific storage location depends on the application client design. If the Token remains valid, there's no need to request a new one from RC.
    • Token validity periods can be configured in the Console, defaulting to permanent validity. Even when generating a new Token, previously issued Tokens remain valid until expiration. After expiration, a new Token must be obtained. If needed, you may actively call the server-side API Invalidate Token.
  • We recommend applications set up connection status monitoring before establishing connections.
  • Ensure SDK initialization is complete.
tip

Never call server-side APIs directly from the client to obtain Tokens. Token retrieval requires providing the App Key and App Secret. If these credentials are stored client-side and the application is decompiled, it could lead to exposure of your App Key and App Secret. Therefore, always ensure Tokens are obtained through your application server.

Connecting to Chat Servers

Determine the appropriate timing (such as during login or registration) to initiate connection requests to RC chat servers based on your application's business requirements and design.

Key considerations:

  • The connect method must be called after SDK initialization; otherwise, callbacks may not be triggered.
  • The SDK has built-in reconnection mechanisms. Avoid calling connect multiple times within a single application lifecycle, as this may trigger multiple callbacks and cause callback clearance.
  • A single call in the application's main process is sufficient.

Interface (with Timeout Setting)

For initial connections to chat servers, we recommend using the interface with connection timeout (timeLimit) and specifying timeout duration in seconds. In cases of connection timeout due to poor network conditions, you can utilize the timeout error callback to notify users through UI elements, such as suggesting they retry when network conditions improve.

Once successfully connected, the SDK's reconnection mechanism takes effect immediately and handles all reconnection processes. When disconnections occur due to network issues, the SDK will continuously attempt reconnection until successful, requiring no additional connection operations from you. Active disconnection by the application will exit the reconnection mechanism (see Disconnection). For other scenarios, refer to Reconnection Mechanism and Multi-Device Kick.

For subsequent offline logins, we recommend setting the timeLimit parameter to 0, allowing page navigation immediately after the database open callback (onDatabaseOpened) to prioritize displaying local historical data, while leaving connection logic entirely to the SDK.

Interface

RongIMClient.connect(token, timeLimit, connectCallback);

Parameter Description

ParameterTypeDescription
tokenStringToken obtained from the server.
timeLimitIntTimeout duration in seconds. No reconnection attempts will be made after timeout. Values ≤ 0 will continue connection attempts until success or business errors occur.
connectCallbackConnectCallbackConnection callback. See Connection Callback Methods for details.
  • Detailed timeLimit parameter explanation:

    • timeLimit ≤ 0: The IM will continue connection attempts until successful or until business errors occur (e.g., invalid Token).
    • timeLimit > 0: The IM will attempt connection for up to timeLimit seconds. If unsuccessful within this period, no further reconnection attempts will be made, and the onError callback will notify of timeout, requiring manual connect calls.

Example Code

public connectIM(String token) {
boolean isCachedLogin == getLoginStatusFromSP(context); // Pseudocode: read login status from sharedpreference
int timeLimit = 0;
if(!isCachedLogin) {
timeLimit = 5;
}
RongIMClient.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 conversation list
} else {
// Database open failed, may display toast notification
}
}

@Override
public void onSuccess(String s) {
// Connection successful; if no navigation occurred during onDatabaseOpened(), may navigate here
}

@Override
public void onError(RongIMClient.ConnectionErrorCode errorCode) {
if (errorCode.equals(RongIMClient.ConnectionErrorCode.RC_CONN_TOKEN_EXPIRE)) {
// Request new token from app server, then reconnect with new token
} else if (errorCode.equals(RongIMClient.ConnectionErrorCode.RC_CONNECT_TIMEOUT)) {
// Connection timeout, display prompt suggesting retry when network improves
} else {
// Handle other business error codes appropriately
}
}
});
}

Interface (with User ID)

tip

This interface is available starting from development version 5.20.0 or stable version 5.7.5.

This enhanced connection interface includes a user ID parameter to facilitate troubleshooting during connection exceptions. Future support will include navigation caching via user ID, offering shorter completion times compared to other connection interfaces. We recommend using this interface.

Interface

RongCoreClient.connect(final String token,
final int timeLimit,
final String userId,
final IRongCoreCallback.ConnectCallback connectCallback);
tip

Developers must ensure this user ID matches the one corresponding to the Token to avoid interference with issue diagnosis.

Interface (No Timeout Setting)

For scenarios where users have previously successfully logged into your application and connected to RC chat servers, we recommend using this interface for subsequent offline logins.

Since users already have historical data, immediate connection success isn't critical. You can navigate pages immediately after the database open callback (onDatabaseOpened) to display local historical data first, leaving connection logic entirely to the SDK.

tip

When network conditions are poor, callbacks may be delayed significantly.

After calling this interface, the SDK's reconnection mechanism takes effect immediately, handling all reconnection processes automatically until successful connection. No additional connection operations are needed. Active disconnection by the application will exit the reconnection mechanism (see Disconnection). For other scenarios, refer to Reconnection Mechanism and Multi-Device Kick.

Interface

RongIMClient.connect(token, connectCallback);

Parameter Description

ParameterTypeDescription
tokenStringUser authentication token obtained from the server.
connectCallbackConnectCallbackConnection callback. See Connection Callback Methods below.

Connection Callback Methods

The connection callback connectCallback provides three callback methods:

  • onDatabaseOpened(DatabaseOpenStatus code)

    Local database open status callback. When DATABASE_OPEN_SUCCESS is returned, the local database is successfully opened, allowing retrieval of local historical conversations and messages—ideal for offline login scenarios.

  • onSuccess(String userId)

    Connection success callback, returning the currently connected user ID.

  • onError(ConnectionErrorCode errorCode)

    Connection failure callback returning corresponding error codes. Refer to Connection Status Codes for appropriate business handling.

    Common errors include:

    • Calling connect() before SDK initialization.

    • App Key mismatch between client and server, causing TOKEN_INCORRECT errors.

      RC provides separate App Key/Secret pairs for production and development environments. Switching from test to production environments may cause App Key mismatches.

    • Token expiration. See Get Token.

Connection Status Codes

The following table lists connection-related status codes. For more codes, see Status Codes.

NameValueDescription
IPC_DISCONNECT-2IPC process terminated unexpectedly.
Possible causes:
1. Mobile system policies causing IPC process recycling or unbinding. Calling RC IM interfaces at the application layer may trigger this issue. The SDK handles automatic reconnection; no additional application handling is required.
2. Missing CPU architecture-specific libRongIMLib.so or libsqlite.so. Ensure all required architecture libraries are integrated.
RC_CONN_ID_REJECT31002Incorrect App Key. Verify the App Key being used.
RC_CONN_TOKEN_INCORRECT31004Invalid Token.
Verify the App Key used for client initialization matches the one used for Token retrieval on your server.
RC_CONN_NOT_AUTHRORIZED31005App verification failed (App verification feature is enabled but verification was unsuccessful).
RC_CONN_APP_BLOCKED_OR_DELETED31008App is blocked or deleted. Verify the App Key being used.
RC_CONN_USER_BLOCKED31009User is blocked. Verify the Token and corresponding UserId.
RC_CONN_TOKEN_EXPIRE31020Token expired.
The Token validity period configured in Console has expired. Request a new Token from your server and establish a new connection.
RC_CONN_PROXY_UNAVAILABLE31028Proxy service unavailable.
RC_CLIENT_NOT_INIT33001SDK not initialized. SDK initialization is required before using any features.
RC_CONNECTION_EXIST34001Connection already exists or is reconnecting.
RC_CONNECT_TIMEOUT34006SDK internal connection timeout. Occurs when using the timeout-enabled connection interface with a valid timeLimit value.
The SDK won't continue reconnection attempts; applications must call connect again.
UNKNOWN-1Unknown error.