Instant messaging connects people wherever they are and allows them to communicate with others in real time. The Agora Chat SDK enables you to embed real-time messaging in any app, on any device, anywhere.
This page shows a sample code to add peer-to-peer messaging into a game by using the Agora Chat SDK for Unity.
The following figure shows the workflow of how clients send and receive peer-to-peer messages.
As shown in the figure, the workflow of peer-to-peer messaging is as follows:
In order to follow the procedure in this page, you must have the following:
This section shows how to prepare the development environment necessary to integrate Agora Chat into your game.
Clone the Unity demo repository to your local device.
In Unity Hub, select the Projects tab, click the down arrow next to the Open button, and select Add project from disk from the drop-down list. In the pop-up window, select the path to the downloaded chat_unity_quickstart
folder under Agora-Chat-API-Examples/Chat-Unity
to add the sample project into Unity Hub.
In the Projects list, select chat_unity_quickstart to open the project.
Go to the SDK download page, and download the latest version of the Agora Chat SDK package for Unity, and decompress it.
In Unity Editor, click Assets > Import Package > Custom Package..., and select the decompressed SDK.
In the Import Unity Package pop-up window, select all the items contained in the SDK, and click Import.
This section shows how to use the Chat SDK to implement peer-to-peer messaging into your game, step-by-step.
In Unity Editor, select the Project tab, select Assets > Scripts, and double-click the TestCode.cs
file.
At the top lines of the TestCode.cs
file, add the following:
using ChatSDK;
using ChatSDK.MessageBody;
In the InitSDK
method, add the following to initialize the SDK:
// In this sample project, initiate the SDK using the App Key of 41117440#383391.
Options options = new Options(APPKEY);
options.UsingHttpsOnly = true;
SDKClient.Instance.InitWithOptions(options);
At the end of the SignUpAction
method, add the following to add the sign-up logic:
StartCoroutine(RegisterAgoraAccount(Username.text, Password.text, (error) =>
{
if (error != null) {
AddLogToLogText(error);
}
else {
AddLogToLogText("register succeed");
}
}));
At the end of the SignInAction
method, add the following to add the login logic:
StartCoroutine(FetchAgoraToken(Username.text, Password.text,
(agornToken) => {
SDKClient.Instance.LoginWithAgoraToken(username: Username.text, agornToken, handle: new CallBack(
onSuccess: () => {
AddLogToLogText("sign in sdk succeed");
},
onError: (code, desc) => {
AddLogToLogText($"sign in sdk failed, code: {code}, desc: {desc}");
}
));
},
(error) => {
AddLogToLogText(error);
}
));
At the end of the SendMessageAction
method, add the following to add the creating and sending logics for messages:
Message msg = Message.CreateTextSendMessage(SignChatId.text, MessageContent.text);
SDKClient.Instance.ChatManager.SendMessage(ref msg, new CallBack(
onSuccess: () => {
AddLogToLogText($"send message succeed, receiver: {SignChatId.text}, message: {MessageContent.text}");
},
onError:(code, desc) => {
AddLogToLogText($"send message failed, code: {code}, desc: {desc}");
}
));
To add the receiving logic for messages, refer to the following steps:
IChatManagerDelegate
class. The sample code is as follows:public class TestCode : MonoBehaviour, IChatManagerDelegate
TestCode
class:public void OnMessagesReceived(List<Message> messages)
{
foreach (Message msg in messages) {
if (msg.Body.Type == MessageBodyType.TXT)
{
TextBody txtBody = msg.Body as TextBody;
AddLogToLogText($"received text message: {txtBody.Text}, from: {msg.From}");
}
else if (msg.Body.Type == MessageBodyType.IMAGE)
{
ImageBody imageBody = msg.Body as ImageBody;
AddLogToLogText($"received image message, from: {msg.From}");
}
else if (msg.Body.Type == MessageBodyType.VIDEO) {
VideoBody videoBody = msg.Body as VideoBody;
AddLogToLogText($"received video message, from: {msg.From}");
}
else if (msg.Body.Type == MessageBodyType.VOICE)
{
VoiceBody voiceBody = msg.Body as VoiceBody;
AddLogToLogText($"received voice message, from: {msg.From}");
}
else if (msg.Body.Type == MessageBodyType.LOCATION)
{
LocationBody localBody = msg.Body as LocationBody;
AddLogToLogText($"received location message, from: {msg.From}");
}
else if (msg.Body.Type == MessageBodyType.FILE)
{
FileBody fileBody = msg.Body as FileBody;
AddLogToLogText($"received file message, from: {msg.From}");
}
}
}
public void OnCmdMessagesReceived(List<Message> messages)
{
}
public void OnMessagesRead(List<Message> messages)
{
}
public void OnMessagesDelivered(List<Message> messages)
{
}
public void OnMessagesRecalled(List<Message> messages)
{
}
public void OnReadAckForGroupMessageUpdated()
{
}
public void OnGroupMessageRead(List<GroupReadAck> list)
{
}
public void OnConversationsUpdate()
{
}
public void OnConversationRead(string from, string to)
{
}
AddChatDelegate
method, add the following:// Add the listener for the `TestCode` object
SDKClient.Instance.ChatManager.AddChatManagerDelegate(this);
RemoveChatDelegate
method, add the following:// Remove the listener when the object is released
SDKClient.Instance.ChatManager.RemoveChatManagerDelegate(this);
In the SignOutAction
method, add the following:
SDKClient.Instance.Logout(true, handle: new CallBack(
onSuccess: () => {
AddLogToLogText("sign out sdk succeed");
},
onError: (code, desc) => {
AddLogToLogText($"sign out sdk failed, code: {code}, desc: {desc}");
}
));
In Unity Editor, select the Project tab, select Assets > Scenes, double-click the SampleScene.cs
file, and click the Play icon at the top of the Unity Editor to run the project.
iOSBuildSetting.cs
file (Path: Assets/ChatSDK/Scripts/Editor
) from the project folder before running the project.If the sample project runs properly, the following user interface appears:
In the user interface, perform the following operations to test the project:
Sign up
Fill in the username in the user id
box and password in the password
box, and click Sign up to register an account. In this example, register two accounts (local_user
and remote_user
) to enable sending and receiving messages.
Log in
After signing up the accounts, fill in the username in the user id
box and password in the password
box, and click Sign in to log in to the app. In this example, log in as local_user
.
Send a message
Fill in the username of the receiver (remote_user
) in the single chat id
box and type in the message ("hello world") to send in the message content
box, and click Send to send the message.
Sign out
Click Sign out to log out of the app.
Receive the message
After signing out as local_user
, log in as remote_user
and receive the message ("hello world") sent in step 3.
You can check the log to see all the operations from this example, as shown in the following figure:
For demonstration purposes, Agora Chat provides an app server that enables you to quickly retrieve a token using the App Key given in this guide. In a production context, the best practice is for you to deploy your own token server, use your own App Key to generate a token, and retrieve the token on the client side to log in to Agora. To see how to implement a server that generates and serves tokens on request, see Generate a User Token.