Skip to main content

Live Streaming Room Scenario Implementation

Prerequisites

Before getting started, ensure you have created an application and completed client SDK integration.

Live Streaming Room Status Management

Live streaming room status typically includes: pending start, live streaming, paused, ended, and replaying. The live streaming room status is maintained by the business side.

Guest Mode

Applicable scenario: Users who have not registered or logged in on the business side enter the live streaming room.

It is recommended to register users to obtain a Token for connecting to RC, and restrict whether guests can send messages on the business side.

Creating and Joining a Chatroom

  1. The application server creates a chatroom via Server API Create Chatroom. After obtaining the chatroom ID, the client can join the chatroom.
  2. By default, the same user cannot join multiple chatrooms simultaneously. You can enable the Single User Joins Multiple Chatrooms feature on the Service Configuration page of the RC Console IM service.
  3. When joining a chatroom, the client SDK can retrieve the latest historical messages (default 10, maximum 50). You cannot pull specific message types via the client SDK, but you can configure Join Chatroom to Retrieve Specified Messages on the Service Configuration page of the RC Console IM service. To pull more messages, enable the Cloud Storage for Chatroom Messages service. To enable this service, please [submit a ticket].

Sample Code:

RongCloud rongCloud = RongCloud.getInstance("appKey", "appSecret");
//Custom API URL method
//RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);
Chatroom chatroom = rongCloud.chatroom;
ChatroomDataModel chatroomDataModel = new ChatroomDataModel().setId("chatroomId3");
ResponseResult result2 = chatroom.createV2(chatroomDataModel);
System.out.println("createV2: " + result2.toString());

FAQs:

  • Can clients directly create chatrooms? No, only the server can create chatrooms.
  • Can users send messages without joining the chatroom? By default, yes. You can enable the SDK Users Cannot Send Messages Without Joining Chatroom feature on the Service Configuration page of the RC Console IM service. Once enabled, users must join the chatroom to send messages.
  • Are other chatroom members notified when a user joins or exits? By default, no. However, you can enable the Chatroom Member Change Monitoring feature. Once enabled, callback notifications will be sent to other chatroom members when users join or exit. This feature can be freely enabled on the Service Configuration page of the RC Console IM service and takes effect after 15 minutes.
  • When a user logs in on multiple devices, does exiting the chatroom on one device log out other devices? By default, no. If you want all devices to exit simultaneously, you can freely enable the Multi-End Simultaneous Online: One End Exits Chatroom, Others Sync Exit feature on the Service Configuration page of the RC Console IM service. It takes effect after 15 minutes.

Chatroom Destruction (Chatroom Keepalive)

  1. Chatrooms have an auto-destruction mechanism. By default, if no users join or send messages within 1 hour, all members are kicked out and the chatroom is destroyed. For details, see Chatroom Destruction Mechanism. You can modify the destruction time by setting the "Auto-Destruction Type," up to 7 days (for specific chatrooms). For details, see Set Chatroom Auto-Destruction Type.
  2. If you also use RTC services, you can bind chatrooms to RTC rooms. When a chatroom meets the preset auto-destruction conditions, the system first checks whether the bound RTC room (RTCRoomId) still exists: if it does, auto-destruction is prevented; if not, the chatroom is destroyed immediately. For details, see Bind to RTC Room.

Chatroom Announcements

Applicable scenario: This feature allows users to view announcements for each live streaming room on the room list page or within the room.

Implement announcements via Chatroom Attribute Management (KV):

  1. Join the chatroom.
  2. Set chatroom announcement information via Chatroom Attribute Management (KV).
  3. Clients retrieve current chatroom announcement information via Get Chatroom KV Attribute.
  4. Use the onChatRoomKVUpdate event in KVStatusListener to synchronize updated chatroom KV attributes, notifying all chatroom members. For details, see Add Chatroom KV Listener.

Client Sample Code:

// Set Chatroom Attribute (KV)
String chatRoomId = "Chatroom ID";
// Chatroom attribute name. Key supports uppercase/lowercase letters, numbers, and special symbols + = - _, with a maximum length of 128 characters.
String key = "Custom chatroom key";//Mic status can also be implemented using Chatroom Attribute (KV).
// Chatroom attribute value, with a maximum length of 4096 characters.
String value = "This is a chatroom announcement";
// true: send notification; false: do not send. If a notification is sent, the SDK will receive a chatroom attribute notification message (ChatRoomKVNotiMessage) with type identifier RC:chrmKVNotiMsg, containing K and V.
boolean sendNotification = false;
// Whether to delete upon exit
boolean isAutoDel = false;
// Custom notification field, valid when sendNotification is true
String notificationExtra = "Custom notification field";

RongChatRoomClient.getInstance().setChatRoomEntry(chatRoomId, key, value, sendNotification, isAutoDel, notificationExtra, new IRongCoreCallback.OperationCallback() {

@Override
public void onSuccess() {

}

@Override
public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {

}
});

//Receiver side:
//Set the chatroom attribute (KV) status listener before joining the chatroom.
RongChatRoomClient.getInstance().addKVStatusListener(new RongChatRoomClient.KVStatusListener() {
@Override
public void onChatRoomKVSync(String roomId) {
//Triggered when chatroom attribute (KV) list synchronization is complete.
}

@Override
public void onChatRoomKVUpdate(String roomId, Map<String, String> chatRoomKvMap) {
//Monitor KV updates via onChatRoomKVUpdate
//Triggered when chatroom attribute (KV) list updates are complete. Returns all KVs during initial sync; subsequent triggers return only added/modified KVs.
}

@Override
public void onChatRoomKVRemove(String roomId, Map<String, String> chatRoomKvMap) {
//Triggered when KVs are deleted.
}
});

Server Code Examples:

RongCloud rongCloud = RongCloud.getInstance("appKey", "appSecret");
// Custom API URL configuration
//RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);
ChatroomEntry entry = rongCloud.chatroom.entry;
ChatroomEntryModel model = new ChatroomEntryModel();
model.setChatroomId("chatroomId1");
model.setUserId("userId1");
model.setKey("key1");
model.setValue("value1");
model.setAutoDelete(0);// Optional
model.setObjectName("RC:TxtMsg");// Optional
model.setContent("{\"key1\":\"value1\"}");// Optional

ResponseResult result = entry.set(model);
System.out.println("chatroomEntrySet Result: " + result.toString());

Chatroom Message Priority

When chatroom message volume is high, the system discards the latest messages exceeding the consumption limit in chronological order to ensure server stability. For details, see Discard Policy.

Chatroom messages are prioritized by importance. Recommended priority order (highest to lowest):

  1. Tipping and gift messages (typically expected to be visible to all users in the live stream)
  2. Text, voice, and image messages
  3. Like messages

You can configure up to 20 low-priority message types. When server load is high, the system preferentially discards low-priority messages. See Chatroom Low-Priority Message Feature.

tip

To protect messages from specific users, use the Chatroom User Allowlist feature to prioritize their messages under all circumstances.

To protect important messages, use the Chatroom Message Allowlist feature.

Chatroom Gift and Like Messages

Use case: Sending gift or like messages in live streams. Implement these message types using Custom Messages.

General Handling Mechanism for Chatroom Gift Messages

  1. Client-Business Server Interaction and Billing: When the client sends a request to the business server via short connection, billing is triggered first. After billing is completed, the gift sender sees "XXX sent XXX gift".

  2. Message Sending After Billing: After billing, the system calls the server API to send custom gift messages.

  3. Message Handling for Continuous Gifting: In scenarios where users send gifts rapidly, sending one message per click may cause server API rate limiting or excessive message volume.

    For continuous gifting, we recommend the following consolidation approach:

    • If users select a specific quantity (e.g., 10 gifts), send one message with the quantity parameter (10 in this case).
    • For rapid consecutive clicks with uncertain final quantity:
      • Consolidate every 20 clicks (adjustable) into one message.
      • If the clicking duration exceeds 1 second, send one message. For example, if a user sends 99 gifts via rapid clicks or direct selection, only 5 messages need to be sent.
  4. High-Frequency Small Gifts with Live Stream Rankings: Use Chatroom Attributes (KV). The app updates click counts to KV every 0.5 seconds, and other chatroom members view the gift leaderboard via KV.

General Handling Mechanism for Chatroom Like Messages

  1. Unlike gift messages, like messages typically don't involve billing and can be sent directly by the client.
  2. The client has a message rate limit (5 messages/second). We recommend consolidating multiple likes within one second into a single message. The application server can obtain like counts via Full Message Routing.

For message sending examples, see Send Messages. Below is sample client code for gift messages:

// Register custom message type (after SDK initialization)
ArrayList<Class<? extends MessageContent>> myMessages = new ArrayList<>();
myMessages.add(CustomMessage.class);
RongCoreClient.registerMessageType(myMessages);


// Message receiving example: Set message listener (automatically triggered when messages arrive)
RongCoreClient.addOnReceiveMessageListener(
new io.rong.imlib.listener.OnReceiveMessageWrapperListener() {
@Override
public boolean onReceivedMessage(Message message, ReceivedProfile profile) {
int left = profile.getLeft();
boolean isOffline = profile.isOffline();
boolean hasPackage = profile.hasPackage();
}
});

// Message object reference (use objectName or content to distinguish message types)
{
conversationType = PRIVATE,
targetId = 'userid3453',
messageId = 70,
channelId = '',
messageDirection = RECEIVE,
senderUserId = 'userid3453',
receivedStatus = io.rong.imlib.model.Message$ReceivedStatus @560f848,
sentStatus = SENT,
receivedTime = 1739428279001,
sentTime = 1739428279158,
objectName = 'gift:CustomMsg',
content = CustomMessage {
giftName = 'Custom gift message', giftCount = 3
},
extra = '',
readReceiptInfo = io.rong.imlib.model.ReadReceiptInfo @b8d3c06,
messageConfig = io.rong.imlib.model.MessageConfig @61092c7,
messageConfig = MessagePushConfig {
disablePushTitle = false,
pushTitle = '',
pushContent = '',
pushData = 'null',
templateId = '',
forceShowDetailContent = false,
iOSConfig = null,
androidConfig = null,
harmonyConfig = null
},
canIncludeExpansion = false,
expansionDic = null,
expansionDicEx = null,
mayHasMoreMessagesBefore = false,
UId = 'CKVO-0J6T-GM26-D3E6',
disableUpdateLastMessage = 'false',
directedUsers = '0'
}

Server Example Code

  RongCloud rongCloud = RongCloud.getInstance("appKey", "appSecret");
//Custom API endpoint configuration
//RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);
Chatroom chatroom = rongCloud.message.chatroom;
String[] chatroomIds = {"chatroom ID"};

GiftCustomTxtMessage ctm = new GiftCustomTxtMessage("Custom Gift",2);
ChatroomMessage chatroomMessage = new ChatroomMessage()
.setSenderId("1")
.setTargetId(chatroomIds)
.setContent(ctm)
.setObjectName(ctm.getType());

ResponseResult chatroomResult = chatroom.send(chatroomMessage);
System.out.println("send chatroom message: " + chatroomResult.toString());

Online User Statistics and Display

To track cumulative view counts, you can use Chatroom Status Sync for statistics.

Live Room Member List and Contribution Ranking

  • Member List
    You can query up to 20 chatroom members (including user IDs and join timestamps) using the client SDK's Get Chatroom Info feature.

  • Contribution Ranking
    Calculate contribution rankings based on your business logic on the server side, then notify chatroom members via Set/Update Chatroom KV Attributes.

Live Room Muting and Banning (Kicking)

Use cases: Restrict user behavior in live rooms according to business requirements.

Chatroom Muting Service

  1. Global Chatroom Mute
    Use Mute All Chatroom Members to prevent all members from sending messages via client SDK. To exempt specific users, add them to the Chatroom Mute Allowlist. Mute data is cleared when the chatroom is dissolved. This feature is free.

    tip
    • Chatroom mute allowlist takes precedence over Global Chatroom Mute.
    • Chatroom mute allowlist is overridden by Global User Mute.
    • Allowlist status persists after users leave the chatroom but becomes invalid if the chatroom is destroyed and recreated.
  2. Global User Mute
    Use Global User Mute to mute specified users across all chatrooms in your application for a set duration. Muted users cannot send messages via client SDK. The Global Chatroom Mute Service is enabled by default in the development environment (dev). In production environments, this feature is supported only for Chat Pro Plan and is not supported for Chat Starter Plan.

  3. Mute Specific Chatroom Users
    Use Mute Chatroom Users to mute 1+ users in specific chatrooms. Muted users can view messages but cannot send them. Mute status persists after users leave the chatroom. This feature is free.

Note: Server API messages are not affected by chatroom mute restrictions.

Client-Side Mute Monitoring Code Samples:

// Set mute listener
//Set mute listener
RongChatRoomClient.addChatRoomNotifyEventListener(
new RongChatRoomClient.ChatRoomNotifyEventListener() {
@Override
public void onChatRoomNotifyMultiLoginSync(ChatRoomSyncEvent event) {
//Multi-device login sync for chatroom join/exit
}

@Override
public void onChatRoomNotifyBlock(ChatRoomMemberBlockEvent event) {
//Chatroom mute/unmute events
}

@Override
public void onChatRoomNotifyBan(ChatRoomMemberBanEvent event) {
//Chatroom ban/unban events
}
});

// Remove

FAQs:

  • How to prevent specific users from speaking in any chatroom?
    Use Global User Mute to restrict specified users from sending messages in all chatrooms.

Muted users can still receive and view messages in chatrooms but cannot send messages. The Global Chatroom Mute Service is enabled by default in the development environment (dev). In production environments, this feature is supported only for Chat Pro Plan and is not supported for Chat Starter Plan.

Chatroom Ban (Kick) Functionality

Using the Ban Chatroom User feature, you can ban one or more users in a specified chatroom (with a maximum of 20 users at a time).

  • If a user is in the chatroom when banned, they will be immediately kicked out.

  • Banned users cannot rejoin the chatroom during the ban period.

  • The ban duration is measured in minutes, with a maximum of 43,200 minutes. For details, see Ban Chatroom User.

FAQs:

  • How to prevent certain users from being automatically kicked out of a chatroom? You can add users to the allowlist to achieve this. A single chatroom supports up to 5 allowlisted users. The Chatroom User Allowlist Service is enabled by default in the development environment (dev). In production environments, this feature is enabled by default for Chat Pro Plan and is not supported for Chat Starter Plan.

  • Why isn't an offline user being kicked out of the chatroom? Chatrooms have an automatic kick mechanism for offline members. The RC server will automatically kick out offline users only if the following default conditions are met:

    1. When the 31st message is sent in the chatroom within 30 seconds after the user goes offline.
    2. When a new message is sent in the chatroom more than 30 seconds after the user goes offline.
    3. If the above conditions are not met but you still want the user to be kicked out, you can submit a ticket to enable the Real-time Kick for Abnormal Chatroom Member Disconnections feature. Once enabled, the server will determine abnormal user status based on SDK behavior and kick out such users within 5 minutes at the latest. This feature is free.

Chatroom Ban User Code Examples:

  RongCloud rongCloud = RongCloud.getInstance("appKey", "appSecret");
Block block = rongCloud.chatroom.block;
ChatroomMember[] members = {
new ChatroomMember().setId("user1"),
new ChatroomMember().setId("user2")
};
ChatroomModel chatroom = new ChatroomModel()
.setId("chatroomid")
.setMembers(members)
.setMinute(5);
ResponseResult result = block.add(chatroom);
System.out.println("addBlockUser: " + result.toString());

Chatroom Broadcast Announcements

Use cases: Celebrity login notifications, full-screen gift notifications for all users, prize-winning announcements, emergency notifications, etc.

You can implement chatroom broadcast announcements through the Send Chatroom Broadcast Message feature. These messages are only received by users currently in the chatroom, and users who join later cannot receive them. The Chatroom Broadcast Message service is enabled by default in the development environment (dev). In production environments, this feature is supported only for Chat Pro Plan and is not supported for Chat Starter Plan.

Chatroom Event Update Scenarios

Use cases: Recording user PK status, mic on/off states, match scores, and other chatroom event updates.

  1. Set custom attributes in specified chatrooms. For example, in voice live streaming chatrooms, use this feature to record attributes of each mic position; Or in card games like Werewolf, record user roles and game states. You can maintain these using Chatroom Attribute Management. Chatroom attributes are stored as Key-Value pairs, supporting set, delete, and query operations, with batch and forced operation capabilities. Client-side configuration is available for Chatroom Attributes. Each chatroom supports up to 100 KVs. This feature is free. For client sample code, see Chatroom Announcements.

  2. To receive real-time attribute changes, configure the Chatroom Custom Attribute Callback URL in the Service Configuration page of RC's IM service Console. This free feature takes effect 15 minutes after activation.