Skip to main content

Quick Integration of Live Chatroom

This tutorial describes how to quickly implement a live chatroom on the web (JavaScript) using the RC IM SDK.

Prerequisites

Create a RC developer account and obtain the App Key.

Step 1: Import the SDK

Install the latest version of the IM SDK using NPM.

npm install @rongcloud/engine@latest @rongcloud/imlib-next@latest -S

Step 2: Initialize the SDK

Create an instance of RongIMLib.

// CMD
const RongIMLib = require('@rongcloud/imlib-next')

// ES
import * as RongIMLib from '@rongcloud/imlib-next'

Pass the App Key in the initialization method. Ensure this process is executed only once. If the App Key does not belong to the China (Beijing) Data Center, you must specify the navigation server and statistics server addresses in the initialization configuration.

RongIMLib.init({ appkey: '<Your-AppKey>', navigators: ['https://nav.sg-light-edge.com'] });
  • Singapore Data Center Navi Server Address: nav.sg-light-edge.com (primary), nav-b.sg-light-edge.com (backup)

Step 3: Add a Message Listener

The application needs to receive messages and notifications through the message listener provided by the SDK. The [addEventListener] method is used to receive various event notifications from IMLib. Multiple listeners can be added for the same event type. The current user will receive all types of messages through this listener.

const Events = RongIMLib.Events
RongIMLib.addEventListener(Events.MESSAGES, (evt) => {
console.log(evt.messages)
})

Step 4: Establish an IM Connection

Before using RC's instant messaging features, you must establish an IM connection with the RC server. The user Token is required to establish the IM connection.

The user Token passed when establishing the IM connection represents the user's unique identifier in RC. You need to maintain the App user registration process, assign a unique user identifier (User ID) to the user, and use this User ID to apply for the Token required to establish the IM connection from RC.

Step 4.1: Obtain the Token

The client SDK does not provide an API to obtain the Token. You need to obtain the Token through the RC server API.

Use the user ID (userId) defined at the App layer to exchange for the identity verification Token used in RC services. The same user ID can be used to obtain the Token multiple times. If the Token is still valid, it can be used to connect to RC services. To re-obtain the Token for the same user ID, use the same interface.

Calling the RC server API requires identity verification. Please add the following HTTP header fields in the request:

  • App-Key: App Key
  • Nonce: Random number
  • Timestamp: Unix timestamp
  • Signature: Concatenate the App Secret, Nonce, and Timestamp in order into a string, and perform SHA1 hash calculation. The App Secret corresponds to the App Key and can be obtained from the Console App Key page.

When obtaining the Token, the HTTP request body needs to include the user ID (userId), name (name), and avatar (portraitUri).

POST /user/getToken.json HTTP/1.1
Host: api.rong-api.com
App-Key: Your_AppKey
Nonce: 14314
Timestamp: 1408710653491
Signature: 45beb7cc7307889a8e711219a47b7cf6a5b000e8
Content-Type: application/x-www-form-urlencoded

userId=jlk456j5&name=Ironman&portraitUri=http%3A%2F%2Fabc.com%2Fmyportrait.jpg

The user ID supports a combination of uppercase and lowercase letters and numbers, with a maximum length of 64 bytes. Note, the name (name) and avatar (portraitUri) are only used for mobile remote push notifications. If new data is passed when re-obtaining the Token, it will overwrite the old name and avatar data.

The returned result will include the passed user ID and the corresponding Token. The Token length is within 256 bytes, and you can cache it within the application.

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{"code":200, "userId":"jlk456j5", "token":"sfd9823ihufi"}

Step 4.2: Connect to the Chat Server

After initialization, you can establish an IM connection by passing the user Token obtained in the previous step.

RongIMLib.connect('<Your-token>').then((res) => {
if (res.code === 0) {
console.log(res.data.userId)
}
})

Once the connection is successful, the SDK's reconnection mechanism takes effect. When the connection is lost due to network issues, the SDK will keep reconnecting until the connection is successful, without requiring additional connection operations from you.

Step 5: Join a Chatroom

In RC's chatroom business, you need to create a chatroom first and then add users to the chatroom so that users can send and receive messages in the chatroom.

Typically, you create a chatroom through the server API, and users generally join the chatroom through the client SDK. To keep this tutorial simple, we will directly call the client's joinChatRoom interface to create and join the chatroom in one step.

const chatRoomId = "chatroomId";
const count = -1;

RongIMLib.joinChatRoom(chatRoomId, {
count: count
}).then(res => {
// Successfully joined the chatroom
if (res.code === RongIMLib.ErrorCode.SUCCESS){
console.log(res.code)
} else {
console.log(res.code, res.msg)
}
}).catch(error => {
console.log(error)
})

The value of the count variable indicates the number of historical messages to retrieve when joining the chatroom. -1 means no historical messages will be retrieved when joining the chatroom.

If joining an existing chatroom, you can call the joinExistChatRoom method.

Step 6: Send Messages

Use the sendMessage method to send messages. Note that the client SDK has a message sending rate limit, with a maximum of 5 messages per second.

Sending a regular message:

// Define the target conversation for message delivery, here we define a chatroom type conversation
const conversation = { conversationType: RongIMLib.ConversationType.CHATROOM, targetId: '<Target ID>' }
// Instantiate the message to be sent, RongIMLib.TextMessage is a built-in text message
const message = new RongIMLib.TextMessage({
// Text content
content: 'Text content',
})

Sending media messages, this tutorial takes sending an image message as an example. This method will first upload media files such as images and videos to RC's default file server (File Storage Duration), and then send the message after the upload is successful.

const conversation = {
conversationType: RongIMLib.ConversationType.CHATROOM,
targetId: 'chatroomId'
}
const msgBody = {
file, // File to be uploaded
}
const hooks = {
onProgress (progress) {}, // Upload progress listener, optional
onComplete (fileInfo) { // Callback hook when upload is complete, optional
console.log(fileInfo.url) // File storage address
// If you need to build a custom message, return new ABCMesssage('')
// ABCMesssage is defined by implementing custom messages `const ABCMesssage = RongIMLib.registerMessageType(...)`
// If there is no return value, the SDK will send an ImageMessage by default
}
}
const options = {
contentDisposition: 'inline' // Optional 'inline' | 'attachment', specifies how the returned link is displayed in the browser, only applicable to App Keys in the global data center (using aws)
// ... Other optional configuration items
},

RongIMLib.sendImageMessage(
conversation,
msgBody,
hooks,
options
).then(({ code, data: message }) => {
if (code === 0) {
// Message sent successfully
}
})

Step 7: Save Historical Messages

After enabling the Cloud Storage for Chatroom Messages service, chatroom messages can be stored on the RC server. The client can directly retrieve messages stored on the server.

const chatRoomId = "chatroomId";
const timestamp = 0;
const count = 10
const order = 0
RongIMLib.getChatroomHistoryMessages(chatRoomId, {
timestamp: timestamp,
count: count,
order: order
}).then(res => {
// Successfully retrieved chatroom historical messages
if (res.code === 0){
console.log(res.code, res.data)
} else {
console.log(res.code, res.msg)
}
}).catch(error => {
console.log(error)
})

timestamp is a Unix timestamp. If it is 0, it means starting the query from the latest time point. order indicates the query order, default is 0, which means retrieving messages with a sentTime earlier (smaller) than the timestamp value. If order is 1, it means retrieving messages with a sentTime later (larger) than the timestamp value.

Step 8: Recall Messages

If an App administrator or a regular user wants to delete a message from all chatroom members' chat history, the recall message feature can be used. After a message is successfully recalled, the original message content will be deleted from all users' local and server historical message records.

const conversation = {
conversationType: RongIMLib.ConversationType.CHATROOM,
targetId: 'chatroomId',
}
RongIMLib.recallMessage(conversation, {
messageUId: 'BS4O-QEBR-VJM6-9GPP',
sentTime: 1632728573423,
})
.then((res) => {
if (res.code === 0) {
console.log(res.code, res.data)
} else {
console.log(res.code, res.msg)
}
})
.catch((error) => {
console.log(error)
})

Step 9: Ban Users

The instant messaging business supports various ban and mute capabilities. The client does not provide related APIs; you can implement them through the server API.

Ban a Specific User

Ban an App user. A single request can ban up to 20 user IDs (userId). The minute parameter represents the ban duration, with a maximum ban duration of 43200 minutes. Once banned, the banned user will be immediately disconnected from the IM connection. During the ban period, the user cannot establish an IM connection with RC and cannot actively use IM services.

  • Ban:

    POST /user/block.json HTTP/1.1
    Host: api.rong-api.com
    App-Key: uwd1c0sxdlx2
    Nonce: 14314
    Timestamp: 1408710653491
    Signature: 45beb7cc7307889a8e711219a47b7cf6a5b000e8
    Content-Type: application/x-www-form-urlencoded

    userId=UserA&minute=10
  • Unban:

    POST /user/unblock.json HTTP/1.1
    Host: api.rong-api.com
    App-Key: uwd1c0sxdlx2
    Nonce: 14314
    Timestamp: 1408710653491
    Signature: 45beb7cc7307889a8e711219a47b7cf6a5b000e8
    Content-Type: application/x-www-form-urlencoded

    userId=UserA

Mute a Chatroom User

The chatroom business supports the mute user feature. A single request can mute up to 20 users (userId) in a specified chatroom (chatroomId). The minute parameter represents the mute duration, with a maximum mute duration of 43200 minutes. Muted users can receive and view chat messages from other users in the chatroom but cannot send messages to the chatroom through the client SDK. Users leaving the chatroom will not invalidate the mute status.

  • Mute:

    POST /chatroom/user/gag/add.json HTTP/1.1
    Host: api.rong-api.com
    App-Key: uwd1c0sxdlx2
    Nonce: 14314
    Timestamp: 1408710653491
    Signature: 45beb7cc7307889a8e711219a47b7cf6a5b000e8
    Content-Type: application/x-www-form-urlencoded

    userId=UserA&chatroomId=16&minute=1
  • Unmute:

    POST /chatroom/user/gag/rollback.json HTTP/1.1
    Host: api.rong-api.com
    App-Key: uwd1c0sxdlx2
    Nonce: 14314
    Timestamp: 1408710653491
    Signature: 45beb7cc7307889a8e711219a47b7cf6a5b000e8
    Content-Type: application/x-www-form-urlencoded

    userId=UserA&chatroomId=16

Mute a Chatroom

The chatroom business supports muting a specified chatroom (chatroomId). After muting, all users in the chatroom cannot send messages to the chatroom through the client SDK. If you need to allow some exception users, you can add them to the chatroom mute allowlist (not covered in this tutorial). If the chatroom is disbanded, the mute data will be cleared.

  • Mute a chatroom:

    POST /chatroom/ban/add.json HTTP/1.1
    Host: api.rong-api.com
    App-Key: uwd1c0sxdlx2
    Nonce: 14314
    Timestamp: 1408710653491
    Signature: 45beb7cc7307889a8e711219a47b7cf6a5b000e8
    Content-Type: application/x-www-form-urlencoded

    chatroomId=123
  • Unmute all members in the chatroom:

    POST /chatroom/ban/rollback.json HTTP/1.1
    Host: api.rong-api.com
    App-Key: uwd1c0sxdlx2
    Nonce: 14314
    Timestamp: 1408710653491
    Signature: 45beb7cc7307889a8e711219a47b7cf6a5b000e8
    Content-Type: application/x-www-form-urlencoded

    chatroomId=123

The chatroom business also supports muting a specified user in all chatrooms under the application, with a mute duration. During the mute period, the muted user cannot send messages through the client SDK in all chatrooms under the application. This feature requires enabling the Chatroom Global Mute service. This tutorial will not cover it.

Appendix: How to Implement Chatroom Likes

You can implement the chatroom like feature using custom messages.

  1. Before calling the connect method, register XappChatroomLike with the SDK.

    const XappChatRoomLike = RongIMLib.registerMessageType('Xapp:Chatroom:Like', true, true, [], false)
  2. When a like is needed, construct a like message and send it using the sendMessage method.

    // Construct the custom message to be sent
    const message = new XappChatroomLike()

    // Send the message
    RongIMLib.sendMessage({
    conversationType: RongIMLib.ConversationType.CHATROOM,
    targetId: 'chatroomId'
    }, message).then(res => {
    if (res.code === 0) {
    console.log(res.code, res.data)
    } else {
    console.log(res.code)
    }
    })
  3. When other users in the chatroom receive messages, check if it is XappChatroomLike. If a like message is received, you can display the like effect in the UI.

    RongCoreClient.addOnReceiveMessageListener(
    new OnReceiveMessageWrapperListener() {
    @Override
    public boolean onReceivedMessage(Message message, int left, boolean hasPackage, boolean offline) {
    MessageContent msgContent = message.getContent();
    if (msgContent instanceof XappChatroomLike) {

    }
    return false;
    }
    });