Send and receive messages
This document describes how to use the ZIM SDK (In-app Chat) to send and receive messages.
Prerequisites
Before you begin, make sure:
-
Go to ZEGOCLOUD Admin Console, and do the following:
- Create a project, get the AppID and AppSign.
- Activate the In-app Chat service (as shown in the following figure).
-
Platform-specific requirements:
- React Native 0.60.0 or later
- A real iOS device that is running on iOS 11.0 or later and supports audio and video.
- An Android device or Simulator that is running on Android 4.0.3 or later and supports audio and video. We recommend you use a real device (enable the "USB Debugging" option).
- Your device is connected to the internet.
- Configure Visual Studio Code, search for the "React Native Tools" extension, and install it.
Integrate the SDK
Optional: Create a new project
Skip to this step if a project already exists.
Import the SDK
The following shows how to integrate the SDK using NPM:
-
Execute the
npm i zego-zim-react-native
oryarn add zego-zim-react-native
command to install the dependencies.NoteWe recommend you use the NPM package that supports the TypeScript language.
-
Import the SDK.
Untitledimport ZIM from 'zego-zim-react-native';
1 -
Go to the iOS root directory, run the
pod install
command to install the dependencies.
After completing the above steps, you can use the zego-zim-react-native
SDK in your project using JavaScript or TypeScript (recommended).
Implementation steps
Get the sample code
Get the sample code from Sample app.
Import the SDK file
Refer to the Integrate the SDK using NPM to import the SDK package file.
Create a ZIM SDK instance
Creating a ZIM instance is the very first step, an instance corresponds to a user logging into the system as a client.
So, let's suppose we have two clients now, client A and client B.
To send and receive messages to each other, both of them will need to call the create method with the AppID in the previous Prerequisites steps to create a ZIM SDK instance of their own:
// Since In-app Chat 2.3.0, the SDK uses the AppSign authentication mode by default. To change the authentication mode:
// 1. For SDK 2.3.3 or later, you can change the authentication mode by yourself. 2. For SDK 2.3.0 or later, if you want to change your authentication mode back to using the Token, contact Technical Support.
// Use a static synchronized method to create a ZIM SDK object and pass the AppID and AppSign.
// The create method creates a ZIM instance only the first time it is called. Any subsequent use will return null.
ZIM.create({ appID: 0, appSign: '' });
// Please get a single instance via the getInstance method to avoid hot updates that return null multiple times using the create method.
var zim = ZIM.getInstance();
Set event callbacks
Before a client user's login, you will need to call the on method to customize the event callbacks, such as you can receive callback notifications when SDK errors occur or receive message-related callback notifications.
// Set up and listen for the callback for receiving error codes.
zim.on('error', function (zim, errorInfo) {
console.log('error', errorInfo.code, errorInfo.message);
});
// Set up and listen for the callback for connection status changes.
zim.on('connectionStateChanged', function (zim, { state, event, extendedData }) {
console.log('connectionStateChanged', state, event, extendedData);
});
// Set up and listen for the callback for receiving one-to-one messages.
zim.on('peerMessageReceived', function (zim, { messageList, info, fromConversationID }) {
console.log('peerMessageReceived', messageList, info, fromConversationID);
});
// Register a callback to listen for "Token is about to expire"
zim.on('tokenWillExpire', function (zim, { second }) {
console.log('tokenWillExpire', second);
// You can call the renewToken interface here to update the token
// For new token generation, please refer to the above
zim.renewToken(token)
.then(function({ token }){
// Update successful
})
.catch(function(err){
// Update failed
})
});
For a detailed introduction to the interfaces, please refer to connectionStateChanged, peerMessageReceived, tokenWillExpire.
Log in to the ZIM SDK
For client A and client B to send, receive messages, and renew the token after creating the ZIM SDK instance, they will need to log in to the ZIM SDK.
To log in, Clients A and B both need to do the following:
- Call the ZIMLoginConfig method to create a user object.
- Then, call the [login](@ login__2) method with their own user information and the Token they get in the previous Prerequisites steps.
-
You can custom the userID and userName, and we recommend you set the userID to a meaningful value and associate them with the account system of your application.
-
For SDK 2.3.0 or later: The SDK uses the AppSign authentication mode by default. You only need to pass the [ZIMUserInfo`](@-ZIMUserInfo) when logging in.
-
If you use the Token-based authentication mode, please refer to the [Authentication](./Guides/Users/Authentication.mdx) to get the Token first, and pass it when logging in.
// userID must be within 32 characters, and can only contain letters, numbers, and the following special characters: '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '-', '`', ';', '’', ',', '.', '<', '>', '/', '\'.
// userName A string of up to 256 bytes, with no restrictions on special characters.
var userInfo = { userID: 'xxxx', userName: 'xxxx' };
var userID = 'xxxx';
var config = {
userName: 'xxxx',
token: '',
}
// When logging in:
// If you use the Token-based authentication, pass the Token you get by referring to the [Guides - Authentication] document.
// If you use the AppSign authentication mode (the default auth mode by SDK 2.3.0), you need to leave the Token field empty.
zim.login(userID, config)
.then(function () {
// Login successful.
})
.catch(function (err) {
// Login failed.
});
Send messages
Client A can send messages to client B after logging in successfully.
The message types currently supported by ZIM are as follows:
消息类型 | 说明 | 特性及适用场景 |
---|---|---|
ZIMCommandMessage(2) | 开发者可自定义数据内容的信令消息。消息大小不超过 5 KB,单个客户端发送频率限制为 10 次/秒。 | 不可存储,支持更高的并发;一般适用于“语聊房”、“在线课堂”等房间内的信令传输,比如上下麦操作、送礼物,发送在线课堂课件等。 相关接口:sendMessage |
ZIMBarrageMessage(20) | 房间内弹幕文本消息。消息大小不超过 5 KB,单个客户端发送频率无限制。 | 不可存储,专门用于房间内的高频、不可靠、允许丢掉的消息,一般适用于发送“弹幕消息”的场景中。 支持高并发,但不可靠,不保证消息送达。 相关接口:sendMessage |
ZIMTextMessage(1) | 文本消息。消息大小不超过 32 KB,单个客户端发送频率限制为 10 次/秒。 | 消息可靠有序,可存储为历史消息(保存时间请参考 计费说明 - 版本说明 中“历史消息存储天数”)。
相关接口:sendMessage、replyMessage |
ZIMMultipleMessage(10) | 组合消息,即包含多个 item 的消息,可包括多条文本、至多 10 张图片、1 个文件、1 个音频、1 个视频和 1 条自定义消息。 说明
| |
ZIMImageMessage(11) | 图片消息。支持主流图片格式,包括 JPG、PNG、BMP、TIFF、GIF、WebP,大小不超过 10 MB,单个客户端发送频率限制为 10 次/秒。 | |
ZIMFileMessage(12) | 文件消息。消息内容为文件,格式不限,大小不超过 100 MB,单个客户端发送频率限制为 10 次/秒。 | |
ZIMAudioMessage(13) | 语音消息。支持 MP3、M4A 格式的语音文件,时长不超过 300 秒,大小不超过 6 MB,单个客户端发送频率限制为 10 次/秒。 | |
ZIMVideoMessage(14) | 视频消息。支持 MP4、MOV 格式的视频文件,大小不超过 100 MB,单个客户端发送频率限制为 10 次/秒。 说明 若要在消息发送成功后获取视频首帧的宽高信息,视频必须使用 H.264 或 H.265 编码格式。 | |
ZIMCombineMessage(100) | 合并消息,消息大小无限制,单个客户端发送频率限制为 10 次/秒。 | |
ZIMCustomMessage(200) | 自定义消息。开发者可自定义消息的类型,并自行完成消息的解析,ZIM SDK 不负责定义和解析自定义消息的具体内容。 |
To send one-to-one messages, for example, if client A wants to send a message to client B, then client A needs to call the sendMessage method with client B's userID, message content, and message type (conversationType).
-
ZIMMessageSentResult: Callback for the results that whether the message is sent successfully.
-
onMessageAttached callback: The callback on the message not sent yet. Before the message is sent, you can get a temporary ZIMMessage message for you to implement your business logic as needed. For example, you can get the ID of the message before sending it. Or when sending a message with large content, such as a video, you can get the localMessageID of the message before the message is uploaded to implement a Loading UI effect.
// The following shows to send a one-to-one message, set the ZIMConversationType to Peer.
var toUserID = 'xxxx1';
var config = {
priority: 1 // Set priority for the message. 1: Low (by default). 2: Medium. 3: High.
};
var type = 0; // Session type. Values are: 0: One-on-one chat. 1: Chat room 2: Group chat.
var notification = {
onMessageAttached: function(message) {
// todo: Loading
}
};
// Send one-to-one text messages.
var messageTextObj = { type: 1, message: 'Text message content' };
zim.sendMessage(messageTextObj, toUserID, type, config, notification)
.then(function ({ message }) {
// Message sent successfully.
})
.catch(function (err) {
// Failed to send the message.
});
Receive messages
After client B logs in, he will receive client A's message through the callback on which is already set in the peerMessageReceived method.
// Set up and listen for the callback for receiving the one-to-one messages.
zim.on('receivePeerMessage', function (zim, { messageList, fromConversationID }) {
console.log('receivePeerMessage', messageList, fromConversationID);
});
Log out
For a client to log out, call the logout method.
zim.logout();
Destroy the ZIM SDK instance
To destroy the ZIM SDK instance, call the destroy method.
zim.destroy();