Send & Receive messages
ZEGOCLOUD's In-app Chat (the ZIM SDK) provides the capability of message management, allowing you to send and receive one-to-one, group, in-room messages, query message history, delete messages, and more. With the message management feature, you can meet different requirements of various scenarios such as social entertainment, online shopping, online education, interactive live streaming, and more.
This document describes how to send and receive messages with the ZIM SDK.
Message types
Message Type | Description | Feature and Scenario |
---|---|---|
ZIMTextMessage(1) | The text message. A text message cannot exceed 32 KB in size, and up to 10 text messages can be sent per second per client. | Text messages are reliable and in order and can be stored as historical messages, applicable to one-to-one chats, group chats, and on-screen comments in chat rooms. After a room is disbanded, messages in it are not stored. API: sendMessage |
ZIMCommandMessage(2) | The signaling message whose content can be customized. A signaling message cannot exceed 5 KB in size, and up to 10 signaling messages can be sent per second per client. | Signaling messages are applicable to signaling transmission (for example, co-hosting, virtual gifting, and course materials sending) in scenarios with a higher concurrency, such as chat rooms and online classrooms. API: sendMessage |
ZIMBarrageMessage(20) | The on-screen comment in a chat room. An on-screen comment cannot exceed 5 KB in size, and there is no limit on the number of comments that can be sent per second per client. | On-screen comments are usually unreliable messages that are sent at a high frequency and can be discarded. A high concurrency is supported, but reliability cannot be guaranteed. API: sendMessage |
ZIMImageMessage(11) | The image message. Mainstream image formats, such as JPG, PNG, BMP, TIFF, GIF, and WebP, are supported. An image message cannot exceed 10 MB in size, and up to 10 image messages can be sent per second per client. | Image messages are reliable and in order and can be stored as historical messages (for 14 days by default), usually applicable to one-to-one chats, chat rooms, and group chats. API: sendMediaMessage |
ZIMFileMessage(12) | The file message. A file message contains a file of any format and cannot exceed 100 MB in size. Up to 10 file messages can be sent per second per client. | |
ZIMAudioMessage(13) | The audio message. An audio message contains an MP3 or M4A audio of up to 300 seconds and cannot exceed 6 MB in size. Up to 10 audio messages can be sent per second per client. | |
ZIMVideoMessage(14) | The video message. A video message contains an MP4 or MOV video and cannot exceed 100 MB in size. Up to 10 video messages can be sent per second per client. The width and height of the first frame of a video can be obtained after successful message sending only if the video is H.264- or H.265-encoded. | |
ZIMCombineMessage(100) | Merge messages, there is no limit on message size, and the sending frequency of a single client is limited to 10 times/second. | Text messages are reliable and in order and can be stored as historical messages, applicable to real-time chat scenarios such as one-to-one chats, room, group chats, etc. API: sendMessage |
ZIMCustomMessage(200) | The custom message. You can customize the message type and parse the message without using the ZIM SDK. | Custom messages are usually applicable to votes, solitaire, and video cards. API: sendMessage |
Send/Receive regular messages
Regular messages refer to the messages of the following message types: ZIMTextMessage, ZIMCommandMessage, and ZIMBarrageMessage.
- To receive event callbacks (receive in-room messages, get the connection status, token expiration, etc.), you can set up the on method and listen for related callbacks.
- When receiving messages, you need to determine the message is a Text message (ZIMTextMessage) or a Command message (ZIMCommandMessage) because these two message types are based on the basic message class (ZIMMessage). You need to convert the basic message class to a concrete message type and then retrieve the message content from the
message
field. - When a message is received, it can be sorted using the message's
orderKey
. The larger theorderKey
, the newer the message. And the number of unread messages will be updated automatically upon receiving.
Send messages
Take client A sending a message to client B as an example:
- Client A and Client B create their own ZIM SDK instances, and set up an event handler on to listen for the receivePeerMessage callback.
- Client A and Client B log in to the ZIM SDK.
- Client A calls the sendMessage method and set the
converversationType
toZIMConversationTypePeer
to send a one-to-one message to Client B. - Client B listens for the receivePeerMessage method to receive Client A's one-to-one messages.
You can't send messages to yourself by calling the sendMessage
method (when toConversationID = your ID). If you did so, the error code 6000001 will return.
// Send one-on-one `Text` message.
var toConversationID = ''; // Peer user's ID.
var conversationType = 0; // Conversation type, 1-on-1 chat: 0. In-room chat: 1. Group chat: 2.
var config = {
priority: 1, // Set message priority. Low: 1 (by default). Medium: 2. High: 3.
};
var messageTextObj = { type: 1, message: 'Message content', extendedData: 'Extension info of the message (optional)' };
var notification = {
onMessageAttached: function(message) {
// todo: Loading
}
}
zim.sendMessage(messageTextObj, toConversationID, conversationType, config, notification)
.then(function ({ message }) {
// c
})
.catch(function (err) {
// Failed to send message.
});
Receive messages
- To send messages, call the sendMessage method and set the
conversationType
accordingly. - To receive messages:
- One-on-one messages (Peer type), through the callbackreceivePeerMessage.
- In-room messages (Room type), through the callback receiveRoomMessage.
- Group messages (Group type), through the callback receiveGroupMessage.
// Callback for receiving the one-to-one message.
zim.on('receivePeerMessage', function (zim, { messageList, fromConversationID }) {
console.log(messageList, fromConversationID);
});
// Callback for receiving the group message.
zim.on('receiveGroupMessage', function (zim, { messageList, fromConversationID }) {
console.log(messageList, fromConversationID);
});
// Callback for receiving the in-room message.
zim.on('receiveRoomMessage', function (zim, { messageList, fromConversationID }) {
console.log(messageList, fromConversationID);
});
Send/Receive rich media content
The ZIM SDK now supports sending and receiving messages of different rich media types, such as images, audio, video, and files. To send and receive rich media content, refer to the following:
- To send rich media content after login, you will need to specify the message type (image, file, audio, video) first and then the session type (one-on-one chat, room chat, group chat).
- For a receiver to receive and download the rich media content, set up and listen for related event callbacks based on the session type (one-on-one chat, room chat, group chat) after logging in.
Send rich media content
To send rich media content after login, call the sendMediaMessage method, and specify the message type (image, file, audio, video), the session type (one-on-one chat, room chat, group chat), and message related configurations as needed.
- When sending rich media content, the file path to be sent must be in
UTF-8
encoding format. - To send rich media content to a room/group, the sender must be in the room/group.
Sample code
Example of sending a local file message
// Sending Rich Media Message with a local file - one-to-one chat
var conversationID = 'xxxx';
var config = { priority: 1 };
var notification = {
onMessageAttached: function(message) {
// todo: Loading
},
onMediaUploadingProgress: function(message, currentFileSize, totalFileSize) {
// todo: upload progress
}
};
function sendMediaMessage(file) {
/* The following code is for demonstration purposes only: please create the corresponding `media message object` based on the requirements and file type in actual development */
// for an image message
var mediaMessageObj = {
fileLocalPath: file,
type: 11,
};
// for a file message
mediaMessageObj = {
fileLocalPath: file,
type: 12,
};
// for an audio message
mediaMessageObj = {
fileLocalPath: file,
type: 13,
audioDuration: 100, // Please fill in the duration of the audio file in seconds (required).
};
// for a video message
mediaMessageObj = {
fileLocalPath: file,
type: 14,
videoDuration: 100, // Please fill in the duration of the video file in seconds (required)
};
zim.sendMediaMessage(
mediaMessageObj,
conversationID,
0,
config,
notification,
);
}
var input = document.createElement('input');
input.type = 'file';
input.onchange = function() {
sendMediaMessage(this.files[0]);
}
Example of sending an online file message
// Sending Rich Media Message with an online file - one-to-one chat
/* When sending an online file message, the ZIM SDK only passes relevant fields to the backend, and the ZIM backend does not save the online file. */
var conversationID = 'xxxx';
var config = { priority: 1 };
var notification = {
onMessageAttached: function(message) {
// todo: Loading
},
onMediaUploadingProgress: function(message, currentFileSize, totalFileSize) {
// todo: upload progress
}
};
/* The following code is for demonstration purposes only: please create the corresponding `media message object` based on the requirements and file type in actual development */
// for an image message
var mediaMessageObj = {
fileDownloadUrl: 'https://xxxx.jpeg', // Original image
thumbnailDownloadUrl: 'https://xxxx-thumbnail.jpeg', //Thumbnail
largeImageDownloadUrl: 'https://xxxx-large.jpeg', // Large picture
type: 11,
};
// for a file message
mediaMessageObj = {
fileDownloadUrl: 'https://xxxx.pdf',
type: 12,
};
// for an audio message
mediaMessageObj = {
fileDownloadUrl: 'https://xxxx.mp3',
type: 13,
audioDuration: 100, // Please fill in the duration of the audio file in seconds (required).
};
// for a video message
mediaMessageObj = {
fileDownloadUrl: 'https://xxxx.mp4',
videoFirstFrameDownloadUrl: 'https://xxxx-firstframe.jpeg', // The image of video first frame
type: 14,
videoDuration: 100, // Please fill in the duration of the video file in seconds (required)
};
zim.sendMediaMessage(
mediaMessageObj,
conversationID,
0,
config,
notification,
);
Example of sending a recorded audio file message
// HTTPS protocol is required.
if (navigator.mediaDevices) {
var chunks = [];
navigator.mediaDevices
.getUserMedia({ audio: true })
.then((stream) => {
var duration = 10; // Duration of recording, in seconds
var mediaRecorder = new MediaRecorder(stream);
mediaRecorder.onstop = function (e) {
// After recording, send the audio message.
var conversationID = 'xxxx';
var config = { priority: 1 };
var notification = {
onMessageAttached: function(message) {
// todo: Loading
},
onMediaUploadingProgress: function(message, currentFileSize, totalFileSize) {
// todo: upload progress
}
};
var mediaMessageObj = {
fileLocalPath: new File(chunks, 'xxxx.mp3'),
type: 13,
audioDuration: duration
};
zim.sendMediaMessage(mediaMessageObj, conversationID, 0, config, notification)
.then((res) => {
// Sent successfully
})
.catch((err) => {
// Sent failed
});
// Reset chunks
chunks = [];
};
mediaRecorder.ondataavailable = function (e) {
chunks.push(e.data);
};
// Start recording
mediaRecorder.start();
// Stop recording
setTimeout(() => mediaRecorder.stop(), duration * 1000);
})
.catch((err) => {
console.log('The following error occured: ' + err);
});
}
Callback for the sending progress of rich media content
To be notified of the sending progress of rich media content, you can set up and listen for the following callback.
Among which:
- message: The content of the message being sent.
- currentFileSize: The size of the message that has been sent.
- totalFileSize: The overall size of the message sent.
Receive rich media content
To receive the rich media content messages, do the following:
- Listen for the following callbacks based on the session type (one-on-one chat, room chat, group chat): receivePeerMessage, receiveRoomMessage, receiveGroupMessage.
- You will then directly get the URL property of the rich media message through the callback you listened for and receive the rich media message.
Send/Receive signaling messages
The ZIM SDK allows you to implement signaling message sending and receiving. You can call the ZIMCommandMessage operation to define the message type, for example, location message.
This message type does not support offline push and local storage.
Below is the sample code for sending a signaling message to a specified user.
Send a signaling message
// The user receives the signaling message.
var toConversationID = ''; // Peer user's ID.
var conversationType = 0; // Conversation type, 1-on-1 chat: 0. In-room chat: 1. Group chat: 2.
var config = {
priority: 1, // Set the message priority. Low: 1 (by default). Medium: 2. High: 3.
};
// Here, the Uint8Array message content is converted into JSON string when the `Command` message is received.
// receivePeerMessage converts the Uint8Array to a JSON string when receiving a Command message of type 2.
var jsonText = JSON.stringify({ id: '111', name: 'Tom' });
var uint8Array = new Uint8Array(Array.from(unescape(encodeURIComponent(jsonText))).map((val) => val.charCodeAt(0)));
var messageCommandObj = { type: 2, message: uint8Array };
var notification = {
onMessageAttached: function(message) {
// todo: Loading
}
}
zim.sendMessage(messageCommandObj, toConversationID, conversationType, config, notification)
.then(function ({ message }) {
// Message sent successfully.
})
.catch(function (err) {
// Failed to send message.
});
Receive the signaling message
// Receive custom messages.
zim.on('receivePeerMessage', function (zim, { messageList, fromConversationID }) {
console.log(messageList, fromConversationID);
messageList.forEach(function (msg) {
// Here, take the JSON string as an example, which needs to be converted to Uint8Array.
if (msg.type == 2) {
var uint8Array = msg.message;
var jsonText = decodeURIComponent(escape(String.fromCharCode(...Array.from(uint8Array))));
var jsonObj = JSON.parse(jsonText);
console.log('receivePeerMessage', jsonObj);
}
})
});
Send/Receive custom messages
The ZIM SDK allows you to implement custom message sending and receiving. You can call the ZIMCustomMessage operation to define the custom message type, for example, the voting message, solitaire message, or video card message. Below is the procedure.
- Only the ZIM SDK 2.8.0 or later supports sending, receiving, and viewing custom messages.
- If the version of the receiving ZIM SDK is 2.0.0 or later but earlier than 2.8.0, the ZIM SDK can receive custom messages but will identify the message type as unknown. In addition, it cannot obtain the message content. To obtain the message content, upgrade the ZIM SDK to 2.8.0 or later.
- If the version of the receiving ZIM SDK is 1.x.x, the ZIM SDK cannot receive custom messages and identify the message type as unknown.
Send a custom message
Call the same operation for sending ordinary messages, that is, sendMessage, to send custom messages. For more information about this operation, see Send/Receive regular messages - Send messages.
You need to call the ZIMCustomMessage operation to define the custom message type,
Below is the sample code for sending a custom message in a one-to-one chat:
// Send a custom message.
// Specify the user ID.
var toConversationID = "xxxx";
var message = ""; // The text message of the custom message.
var subType = 100; // The subtype of the custom message.
var searchedContent = "";// The searched content of the custom message.
var zimCustomMessage = {
type: 200,
message: message,
subType: subType,
searchedContent: searchedContent
};
// The advanced attribute for message sending.
var conversationType = 0; // The conversation type. Valid values: 0: one-to-one chat; 1: chat room; 2: group chat.
var config = {
priority: 1, // Specify the message priority. Valid values: 1 (default): low; 2: medium; 3: high.
};
zim.sendMessage(zimCustomMessage, toConversationID, conversationType, config).then(function ({ message }) {
// Sending succeeded.
})
.catch(function (err) {
// Sending failed.
});
Receive custom messages
Call the same operation for receiving ordinary messages to receive custom messages. For more information about this operation, see Send/Receive regular messages - Receive messages.
Below is the sample code for receiving a custom message in a one-to-one chat:
// The user receives the custom message in the one-to-one chat.
zim.on('receivePeerMessage', function (zim, { messageList, fromConversationID }) {
console.log(messageList, fromConversationID);
messageList.forEach(function (msg) {
// The `Custom` message is received.
if (msg.type == 200) {
}
})
});
Send and receive mentioned messages
A mentioned message contains the @ symbol and the mentioned user who will be notified of the message.
A mentioned message is not a message type. A text message can also be a mentioned message.
Send a mentioned message
When calling the sendMessage operation to send a message, you can specify the MentionedUserIDs parameter of ZIMMessage to set the message to a mentioned message:
- mentionedUserIDs: It notifies the mentioned user (who can be out of the conversation) of the message. The parameter can contain up to 50 bytes in length. If you need a longer length, contact ZEGO technical support.
- isMentionAll: It notifies all other users in a conversation of the message.
Only the ZIM SDK 2.14.0 or later supports sending mentioned messages.
// Below is the sample code for sending a mentioned message (text message) in a one-to-one chat:
var toConversationID = ''; // The ID of the other user.
var conversationType = 0; // The conversation type. Valid values: 0: one-to-one chat; 1: chat room; 2: group chat.
var config = {
priority: 1, // Specify the message priority. Valid values: 1 (default): low; 2: medium; 3: high.
};
var messageTextObj = { type: 1, message: 'Text message content', extendedData: 'Optional: extended information of the message' };
// Call the operation to notify users in the list of the message.
message.mentionedUserIDs = ["userId1", "userId2"];
// Notify all other users in the conversation of the message.
message.isMentionAll = true;
var notification = {
onMessageAttached: function(message) {
// todo: Loading
}
}
zim.sendMessage(messageTextObj, toConversationID, conversationType, config, notification)
.then(function ({ message }) {
// Sending succeeded.
})
.catch(function (err) {
// Sending failed.
});
Receive a mentioned message
Call the same operation for receiving ordinary messages to receive mentioned messages. For more information about this operation, see Send and receive ordinary messages - Receive messages.
After messages are received, you can implement features, for example, highlighting, based on the business logic.
- Only the ZIM SDK 2.14.0 or later supports receiving and viewing mentioned messages.
- If the version of the receiving ZIM SDK is 2.0.0 or later but earlier than 2.14.0, the received message does not contain the mentioned content.
- If the version of the receiving ZIM SDK is 1.x.x, mentioned messages cannot be received.
Obtain the mentionedInfoList
After a user in a conversation is notified, the mentionedInfoList can be obtained manually or automatically.
mentionedInfoList: It contains the mentioned message ID, sender ID, and the mentioned message type. ZIMMessageMentionedType: You can specify this parameter to implement various business logics, for example, mentioning.
Automatic obtaining
If a user is notified, the conversationChanged callback is received, which can be used to obtain the latest mentionedInfoList of the ZIMConversation.
zim.on('conversationChanged', function (zim, { info }) {
565 + console.log(info);
});
Manual obtaining
If the queryConversationList or queryConversation operation is called to pull a conversation, the mentionedInfoList in the conversation is also obtained. Below is the sample code:
var mentionedInfoList = conversaion.mentionedInfoList;
Clear the mentionedInfoList of a conversation
After a mentioned message is received, the mentioned user needs to clear the mentionedInfoList to get rid of the notification.
The operation for clearing the mentionedInfoList of a conversation is the same as that for clearing the number of unread messages of a conversation.
- clearConversationUnreadMessageCount: It clears the number of unread messages of a conversation. For more information, see Conversation management - Clear the number of unread messages in a conversation.
- clearConversationTotalUnreadMessageCount: It clears the number of unread messages of all conversations. For more information, see Conversation management - Clear the numbers of unread messages in all conversations.
Obtain the list of mentioned users
All users in a conversation can obtain the list of mentioned users with the MentionedUserIDs parameter of the ZIMMessage, that is, the list of users passed in with the MentionedUserIDs parameter of the ZIMMessage by the sender.
var userIds = message.mentionedUserIDs;
Check whether to mention all.
All users in a conversation can call the isMentionAll operation to check whether a message mentions all.
var isMentionAll = message.isMentionAll;
Send and receive a message that mentions all
The ZIM SDK allows you to send a message to all online users from the server and allows these users to receive the message from the client.
Send a message to all users from the server
For more information about how to send a message to all users from the server, see Push Message To All Users.
Receive a message that mentions all from the server
- Only the ZIM SDK 2.10.0 or later supports receiving and viewing a message that mentions all.
- If the version of the receiving ZIM SDK is 2.0.0 or later but earlier than 2.10.0, the ZIM SDK cannot receive the message that mentions all from the server. To receive the message, upgrade the ZIM SDK to 2.10.0 or later.
To receive a message that mentions all, call the broadcastMessageReceived operation.
Sample code:
// Users receive the message that mentions all.
zim.on('broadcastMessageReceived', function (zim, { message }) {
console.log(message);
});
Forward message
The ZIM SDK supports forwarding messages in one of the following ways:
- Combining messages and forwarding the combined message.
- Forwarding messages one by one.
For more information, see Forward messages.
Receive Tips message
ZIM SDK supports converting user operations within a session into Tips messages. When a related operation occurs, ZIM SDK will send a Tips message to the session to notify. For details, please refer to Receive tip messages.
Listen for the message status
On a weak network condition, this may happen: the ZIM SDK doesn't receive the response from the server for some reason (e.g., packet loss), while the message is successfully sent. In this case, the ZIM SDK considers the message sending failed due to the reply timeout, but the message is actually sent successfully, which results in message status confusion. To solve this and Clarify the message status, the SDK 2.6.0 or later now allows you to listen for the messageSentStatusChanged callback to receive the changes of the message status. And we now have three different message statuses: Sending = 0, Success = 1, and Failed = 2. You can know whether your message is sent successfully by the status, and implement your event handling logic as needed.
// Listen for the message status.
zim.on('messageSentStatusChanged', function (zim, result) {
result.infos.forEach( function (info) {
console.warn(info.message, info.status);
});
});