Connect
The client must successfully connect to the chat server before it can send and receive messages.
Prerequisites
- You have obtained a user token from your application server.
- You have completed SDK initialization (
NCChatUI.initialize(...)). - We recommend setting up connection status monitoring first. See Monitor connection status.
Connect to the chat server
The Chat UI SDK provides the following connection method:
- Kotlin
- Java
kotlin
NCChatUI.connect(params, handler)
Java
NCChatUI.connect(params, handler);
Parameters
| Parameter | Type | Description |
|---|---|---|
params | ConnectParams | Connection parameters. token is required; timeout and reconnectKickEnable are optional. |
handler | ConnectHandler | Connection result callback. Can be null. |
ConnectParams fields:
| Field | Type | Description |
|---|---|---|
token | String | User identity token issued by your server (required). |
timeout | int | Connection timeout in seconds. Default is -1 (SDK default behavior). |
reconnectKickEnable | boolean | Whether to keep existing online devices during reconnection conflicts. Default is false. |
Example
- Kotlin
- Java
kotlin
val token = "user_token"
val params = ConnectParams(token).apply {
timeout = 10 // Optional: connection timeout in seconds
reconnectKickEnable = false // Optional
}
NCChatUI.connect(params, object : ConnectHandler {
override fun onDatabaseOpened(isRecreated: Boolean, error: NCError?) {
if (error == null) {
// Local database is ready; you can display cached channels and messages
}
}
override fun onResult(userId: String?, error: NCError?) {
if (error == null) {
// Connection successful
} else {
// Connection failed: error.code / error.message
}
}
})
Java
String token = "user_token";
ConnectParams params = new ConnectParams(token);
params.setTimeout(10); // Optional: connection timeout in seconds
params.setReconnectKickEnable(false); // Optional
NCChatUI.connect(params, new ConnectHandler() {
@Override
public void onDatabaseOpened(boolean isRecreated, NCError error) {
if (error == null) {
// Local database is ready; you can display cached channels and messages
}
}
@Override
public void onResult(String userId, NCError error) {
if (error == null) {
// Connection successful
} else {
// Connection failed: error.getCode() / error.getMessage()
}
}
});
Callbacks
ConnectHandler provides two callbacks:
onDatabaseOpened(boolean isRecreated, NCError error)- Called when the local database is opened.
error == nullindicates the database is ready.
onResult(String userId, NCError error)- Called when the connection attempt completes.
error == nullindicates success. Otherwise, check the error code and message.
Notes
- You must call
connect()after SDK initialization. - Typically, you only need to connect once per application lifecycle. The SDK handles reconnection automatically when the network is interrupted.
- To disconnect manually, use
NCChatUI.disconnect()orNCChatUI.logout(). See Disconnect.