logo
In-app Chat
SDK Error Codes
Powered Byspreading
On this page

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 and listen for the message status with the ZIM SDK.

Message types

Message TypeDescriptionFeature 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 and ZIMBarrageMessage.

Warning
  • 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 callback.
  • 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 the orderKey, the newer the message. And the number of unread messages will be updated automatically upon receiving.

Send messages

The following process shows how Client A sends one-to-one messages to Client B:

  1. Client A and Client B create their own ZIM SDK instances, and set up an event handler on to listen for the callback receivePeerMessage.
  2. Client A and Client B log in to the ZIM SDK.
  3. Client A calls the sendPeerMessage method and set the converversationType to ZIMConversationTypePeer to send a one-to-one message to Client B.
  4. Client B listens for the receivePeerMessage method to receive Client A's one-to-one messages.
Warning

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.

SampleCode
// 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 }) {
        // Extension info of the message (optional)
    })
    .catch(function (err) {
        // Extension info of the message (optional)
    });
1
Copied!

Receive messages

Note
SampleCode
// 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);
});
1
Copied!

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:

  1. 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).
  2. 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.

Warning
  • 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.
SampleCode
// Send network files - one-on-one chat: 
/* When sending network file messages, the ZIM SDK only transparently transmits related fields to the background, and the ZIM background does not save network files. */

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 only an example: when developing, create the corresponding `media message object` according to the actual requirements and file types */
/* Note: fileLocalPath is the absolute path of the local file. */
 var fileLocalPath = '/sdcard/xxxx';

// Send images:
var mediaMessageObj = {
    fileDownloadUrl: 'https://xxxx.jpeg', //  Full Image
    thumbnailDownloadUrl: 'https://xxxx-thumbnail.jpeg', // Thumbnail
    largeImageDownloadUrl: 'https://xxxx-large.jpeg', // Large image
    type: 11,
};
// Send files:
mediaMessageObj = {
    fileDownloadUrl: 'https://xxxx.pdf',
    type: 12,
};
// Send audios:
mediaMessageObj = {
    fileDownloadUrl: 'https://xxxx.mp3',
    type: 13,
    audioDuration: 100, // Please fill in the audio file playback duration, in seconds (required).
};
// Send videos:
mediaMessageObj = {
    fileDownloadUrl: 'https://xxxx.mp4',
    videoFirstFrameDownloadUrl: 'https://xxxx-firstframe.jpeg', // First frame image of the video.
    type: 14,
    videoDuration: 100, // Please fill in the video file playback duration, in seconds (required).
};
  
zim.sendMediaMessage(
    mediaMessageObj,
    conversationID,
    0,
    config,
    notification,
);
1
Copied!

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:

  1. Listen for the following callbacks based on the session type (one-on-one chat, room chat, group chat): receivePeerMessage, receiveRoomMessage, receiveGroupMessage.
  2. Call the downloadMediaFile method to download the rich media content.

When downloading rich media content, you need to specify the file type of the corresponding media messages first.

  • Image messages: You can choose to download the original file, large view, or thumbnail.
  • Files/Audio messages: Only original files/audio files can be downloaded.
  • Video messages: You can choose to download the original video file and the thumbnail of the first frame of the video.

Send & Receive signaling messages

The ZIM SDK now supports you to send and receive signaling messages. To do that, you can call the ZIMCommandMessage to define the message type you want to send, for example, your location information.

Note

This message type does not support offline push and local storage.

The following shows how to send signaling messages to a specified user.

Send signaling messages

SampleCode
//  Send signaling messages to a specified user. 

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.
    });
1
Copied!

Receive signaling messages

SampleCode
//  Receive signaling 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);
        }
    })
});
1
Copied!

Send & receive custom messages

ZIM SDK supports developers to implement custom types of message sending and receiving. Developers can define message types by themselves through calling ZIMCustomMessage , such as voting type, chain reaction type, video card type, etc. Developers can use the following steps to send and receive custom messages.

Note
  • Only ZIM SDK version 2.8.0 and above supports sending custom messages, receiving and viewing the content of custom messages.
  • If the SDK version of the receiving end is between [2.0.0, 2.8.0), the custom message can be received, but the message type will be displayed as unknown and the information content cannot be obtained. To get this message, please upgrade the SDK to version 2.8.0 or above.
  • If the SDK version of the receiving end is version 1.x.x, you cannot receive custom messages or unknown messages.

Send custom messages

The interface used to send custom messages is sendMessage, which is the same as the interface used to send ordinary messages. Developers can refer to Send & Receive regular messages - Send messages to learn about the interface parameter details.

Developers need to define custom messages through calling ZIMCustomMessage,

The following is sample code for a user to send a custom message in a one-to-one chat:

Untitled
// Send custom messages
// Specify user ID
var toConversationID = "xxxx";
var message = "";  // Text content of custom messages
var subType = 100;  // Specific custom type
var searchedContent = ""; // Retrieval field for custom messages.

var zimCustomMessage = {
    type: 200, 
    message: message,
    subType: subType,
    searchedContent: searchedContent
};

// Advanced property configuration for sending messages
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. 
};

zim.sendMessage(zimCustomMessage, toConversationID, conversationType, config).then(function ({ message }) {
        // Message sent successfully.
    })
    .catch(function (err) {
        // Failed to send message.
  });
1
Copied!

Receive custom messages

The callback interface for receiving custom messages is the same as that of receiving regular messages. Please refer to Send & Receive regular messages - Receive messages to learn about the specific interfaces.

The following is sample code for users to receive custom messages in a one-to-one chat:

Untitled
// Users receive custom messages in a one-to-one chat.
zim.on('receivePeerMessage', function (zim, { messageList, fromConversationID }) {
    console.log(messageList, fromConversationID);
    messageList.forEach(function (msg) {
        // When a `Custom` message is received.
        if (msg.type == 200) {
      }
    })
});
1
Copied!

Send & receive @ messages

@ messages refer to messages that contain content with "@" followed by a user's name. Users who are mentioned with @ in a message will receive a strong notification when they receive the message.

Note

@ messages are not a separate message type. A message can be a text message or any other type of message, and it can also be an @ message.

Send @ messages

When calling sendMessage to send a message, you can set a message as an @ message using the following ZIMMessage parameters (can be used simultaneously):

  • mentionedUserIDs:Notify specific users (including users outside the conversation) to view the message. The length of the provided userID list can be up to 50. If you need to increase this limit, please contact ZEGOCLOUD technical support.
  • isMentionAll:Notify all other users in the conversation to view the message.
Note

@ message support is only available in ZIM SDK version 2.14.0 and above.

Untitled
// The following is sample code for a user to send an @ message (text message) in a one-to-one chat:
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)' };

// Call the interface to remind users in the list to view messages.
message.mentionedUserIDs = ["userId1", "userId2"];

// Remind all other users in the session to view the message.
message.isMentionAll = true;

var notification = {
    onMessageAttached: function(message) {
        // todo: Loading
    }
}

zim.sendMessage(messageTextObj, toConversationID, conversationType, config, notification)
  .then(function ({ message }) {
      // Message sent successfully.
    })
    .catch(function (err) {
      // Failed to send message.
    });


1
Copied!

Receive @ Messages

The callback interface for receiving @ messages is the same as the callback interface for receiving regular messages. Please refer to Receive regular messages - Receive messages to learn about the specific interfaces.

After receiving the message, developers can implement corresponding functions based on business logic, such as highlighting.

Note
  • Only ZIM SDK versions 2.14.0 and above support receiving and viewing the content of @ messages.
  • If the SDK version on the receiving end is between [2.0.0, 2.14.0), the received messages and conversations will not contain @ information.
  • If the SDK version on the receiving end is version 1.x.x, @ messages cannot be received.

Receive mentionedInfoList

When the user in the session is reminded, mentionedInfoList can be obtained passively or actively.

mentionedInfoList, contains the corresponding message ID of the @ message, the sender userID, and the type of the @ message ZIMMessageMentionedType, which developers can use to implement marking conversations, etc. Various business logic.

Passively obtain

When the user is reminded, he/she will receive the conversationChanged callback and can obtain the latest mentionedInfoList of the current ZIMConversation.

Untitled
zim.on('conversationChanged', function (zim, { info }) {
    console.log(info);
});
1
Copied!

Actively obtain

If you use queryConversationList or queryConversation to actively pull the conversation, you can also get the mentionedInfoList in the conversation. Please refer to the following Sample code:

Untitled
var mentionedInfoList = conversaion.mentionedInfoList;
1
Copied!

Clear the mentionedInfoList of the session

After receiving the @ message, the user needs to clear the mentionedInfoList of the session in order to no longer be reminded.

The mentionedInfoList interface for clearing a session is the same as the interface for clearing unread session messages:

Get reminder user list

All users in the session can obtain the specific reminder user list through the mentionedUserIDs parameter of ZIMMessage. However, this interface can only return the user list passed in by the sending user through the mentionedUserIDs parameter of ZIMMessagefor @ messages.

Untitled
var userIds = message.mentionedUserIDs;
1
Copied!

Confirm whether it is a reminder for all members

All users in the session can call the isMentionAll interface to confirm whether the message is a reminder message for all members.

Untitled
var isMentionAll = message.isMentionAll;
1
Copied!

Send & receive broadcast messages to all members

ZIM allows you to send messages to all online users of the App through the server, and the target users receive relevant messages through the client.

Send messages to all users from the server

Please refer to the API documentation Push messgae to all users to implement sending messages to all users from the server-side.

Receive broadcast messages from the server

Note
  • Only ZIM SDK versions 2.10.0 and above support receiving and viewing the content of broadcast messages.
  • If the SDK version on the receiving end is between [2.0.0, 2.10.0), broadcast messages from the server cannot be received. To receive these messages, please upgrade the SDK to version 2.10.0 or above.

Through calling the broadcastMessageReceived callback, you can receive broadcast messages.

Sample code:

Untitled
// 用Users receive broadcast messages
zim.on('broadcastMessageReceived', function (zim, { message }) {
    console.log(message);
});
1
Copied!

Forward messages

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.

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.

Untitled
// Listen for the message status.
zim.on('messageSentStatusChanged', function (zim, result) {
  result.infos.forEach( function (info) {
      console.warn(info.message, info.status);
  });  
});
1
Copied!

Previous

Manage group members

Next

Get message history