SDK quickstart
Updated
A highly reliable global communication platform where users can chat one-to-one, in groups or in chat rooms.
Instant messaging enhances user engagement by enabling users to connect and form a community within the app. Increased engagement can lead to increased user satisfaction and loyalty to your app. An instant messaging feature can also provide real-time support to users, allowing them to get help and answers to their questions quickly. The Chat SDK enables you to embed real-time messaging in any app, on any device, anywhere.
This page guides you through implementing peer-to-peer messaging into your app using the Chat SDK.
Understand the tech
The following figure shows the workflow of sending and receiving peer-to-peer messages using Chat SDK.
Chat SDK workflow
- Clients retrieve an authentication token from your app server.
- Users log in to Chat using the App ID, their user ID, and token.
- Clients send and receive messages through Chat as follows:
- Client A sends a message to Client B. The message is sent to the Agora Chat server.
- The server delivers the message to Client B. When Client B receives a message, the SDK triggers an event.
- Client B listens for the event to read and display the message.
Prerequisites
In order to follow the procedure on this page, you must have:
-
A valid Agora account.
-
An Agora project for which you have enabled Chat.
-
The App ID for the project.
-
Internet access.
Ensure that no firewall is blocking your network communication.
Project setup
-
Create a Unity project:
-
In Unity Hub, select Projects, then click New Project.
-
In All templates, select 3D. Set the Project name and Location, then click Create Project.
Your project opens in Unity Editor.
-
-
Integrate Chat SDK into your project:
-
Unzip Chat SDK for Unity to a local folder:
-
In Unity, click Assets > Import Package > Custom Package.
-
Navigate to the Chat SDK package and click Open.
-
In Import Unity Package, click Import.
-
Implement peer-to-peer messaging
This section shows how to use the Chat SDK to implement peer-to-peer messaging in your app, step by step.
Create the UI
In the quick start app, you create a simple UI that consists of the following elements:
- A
Button - TextMeshProto log in or out of Agora Chat. - An
Input Field - TextMeshProto specify the recipient user ID. - An
Input Field - TextMeshProto enter a text message. - A
Button - TextMeshProto send the text message. - A
Scroll Viewto display all sent and received messages.
To implement this user interface, in your Unity project:
-
Set up the Scroll View
-
In Unity Editor, right-click Sample Scene, then click Game Object > UI > Scroll View. A scroll view appears in the Scene Canvas. In Inspector, rename the Scroll View to
scrollView.If you can't see the view clearly in Unity, zoom out and rotate the scene
-
To adjust the
scrollViewsize, change the following coordinates in Inspector:- Pos X -
0 - Pos Y -
0 - Width -
250 - Height -
300
- Pos X -
-
In Hierarchy select scrollView > Viewport > Content. In Inspector click Add Component and choose Layout > Vertical Layout Group.
-
In Inspector click Add Component again, and select Layout > Content Size Fitter. Set the Vertical fit property of the component to
Preferred Size. -
In Inspector click Add Component again, and select UI > TextMeshPro - Text (UI). In the TMP Importer pop-up, click Import TMP Essentials. Your project imports the required components to your project. Expand the TextMeshPro - Text component properties and under Extra Settings set the Left, Top, Right and Bottom margins to
10.
-
-
Add a login button
-
In Hierarchy, right-click Sample Scene, then click UI > Button - TextMeshPro. A button appears in the Scene Canvas. In Inspector, rename Button to
joinBtn, then change the following properties:- Pos X -
89 - Pos Y -
160 - Width -
70 - Height -
30
- Pos X -
-
Select the Text (TMP) sub-item of
joinBtnand in Inspector, change Text toJoin.
-
-
Add a send button
-
Right-click Sample Scene, then click UI > Button - TextMeshPro. A button appears in the Scene Canvas. In Inspector, rename Button to
sendBtn, then change the following properties:- Pos X -
97 - Pos Y -
-162 - Width -
57 - Height -
30
- Pos X -
-
Select the Text (TMP) sub-item of
sendBtnand in Inspector, change Text to>>.
-
-
Add input fields to enter a message and a recipient user ID
-
Right-click Sample Scene, then click UI > Input Field - TextMeshPro. An input field appears in the Scene Canvas. In Inspector, rename InputField (TMP) to
message, and change the following coordinates:- Pos X -
-27 - Pos Y -
-162 - Width -
195 - Height -
30
- Pos X -
-
Repeat the procedure in the previous step to add another input field named
userName. In Inspector set the following coordinates:- Pos X -
-35 - Pos Y -
160 - Width -
180 - Height -
30
- Pos X -
-
Handle the system logic
In this section, you create a script file, add the necessary namespaces, and bind your script to the canvas.
-
Create a new script
-
In Project, open Assets > AgoraChat > Scripts. Right-click Scripts, then click Create > C# Script. In Assets, you see the
NewBehaviourScriptfile that you use to implement Chat SDK in your app. -
In Inspector, click Open.
NewBehaviourScript.csopens in your default text editor.
-
-
Import the relevant Agora and Unity classes
In
NewBehaviourScript.cs, add the following lines afterusing UnityEngine;:using UnityEngine.UI; using TMPro; using AgoraChat; using AgoraChat.MessageBody; -
Bind your script to the canvas
-
Drag
NewBehaviourScript.csfromAssets/AgoraChat/Scripts, and drop it on to Canvas in the Hierarchy. -
Click Canvas, you see that your script is added to Canvas in Inspector.
-
Send and receive messages
When a user opens the app, you instantiate and initialize a SDKClient. When the user taps the Join button, the app logs in to Agora Chat. When a user types a message in the text box and then presses >>, the typed message is sent to Agora Chat. When the app receives a message from the server, the message is displayed in the message list. This simple workflow enables you to rapidly build a Chat client with basic functionality.
The following figure shows the API call sequence for implementing this workflow.
API call sequence
To implement this workflow in your app, take the following steps:
-
Declare variables
In the
NewBehaviourScriptclass, add the following declarations:private TMP_Text messageList; private string userId = ""; private string token = ""; private string appId = ""; private bool isJoined = false; SDKClient agoraChatClient; -
Set up Chat when the app starts
When the app starts, you set up a
SDKClientand callbacks to handle Chat events. To do this, replace theStartmethod in theNewBehaviourScriptclass with the following:void Start() { GameObject.Find("userName/Text Area/Placeholder").GetComponent<TMP_Text>().text = "Enter recipient name"; GameObject.Find("message/Text Area/Placeholder").GetComponent<TMP_Text>().text = "Message"; messageList = GameObject.Find("scrollView/Viewport/Content").GetComponent<TextMeshProUGUI>(); messageList.fontSize = 14; messageList.text = ""; GameObject button = GameObject.Find("joinBtn"); button.GetComponent<Button>().onClick.AddListener(joinLeave); button = GameObject.Find("sendBtn"); button.GetComponent<Button>().onClick.AddListener(sendMessage); setupChatSDK(); } -
Instantiate the
SDKClientTo implement peer-to-peer messaging, you use Chat SDK to initialize a
SDKClientinstance. In theNewBehaviourScriptclass, add the following method beforeStart.void setupChatSDK() { if (appId == "") { Debug.Log("You should set your App ID first!"); return; } // Initialize the Agora Chat SDK Options options = Options.InitOptionsWithAppId(appId); options.UsingHttpsOnly = true; options.DebugMode = true; agoraChatClient = SDKClient.Instance; agoraChatClient.InitWithOptions(options); } -
Handle and respond to Chat events
To receive notification of Chat events such as connection, disconnection, and token expiration, you use
IChatManagerDelegateandIConnectionDelegate. When you receive theonMessageReceivednotification, you display the message to the user. To implement these notifications in your app, do the following:-
In the
NewBehaviourScriptclass, add the following at the end ofsetupChatSDK:agoraChatClient.ChatManager.AddChatManagerDelegate(this); -
Implement the
IChatManagerDelegateandIConnectionDelegateinterfaces in theNewBehaviourScriptclass. InNewBehaviourScript.cs, add the following afterpublic class NewBehaviourScript : MonoBehaviour:, IChatManagerDelegate, IConnectionDelegate -
In the
NewBehaviourScriptclass, add the following callbacks beforesetupChatSDK:public void OnMessagesReceived(List<Message> messages) { foreach (Message msg in messages) { if (msg.Body.Type == MessageBodyType.TXT) { TextBody txtBody = msg.Body as TextBody; string Msg = msg.From + ":" + txtBody.Text; displayMessage(Msg, false); } } } public void OnCmdMessagesReceived(List<Message> messages) { // This callback is triggered only by the reception of a command message that is usually invisible to users. } public void OnMessagesRead(List<Message> messages) { // Occurs when a read receipt is received for a message. } public void OnMessagesDelivered(List<Message> messages) { // Occurs when a delivery receipt is received. } public void OnMessagesRecalled(List<Message> messages) { // Occurs when a received message is recalled. } public void OnReadAckForGroupMessageUpdated() { // Occurs when the read status updates of a group message is received. } public void OnGroupMessageRead(List<GroupReadAck> list) { // Occurs when a read receipt is received for a group message. } public void OnConversationsUpdate() { // Occurs when the number of conversations changes. } public void OnConversationRead(string from, string to) { // Occurs when the read receipt is received for a conversation. } public void MessageReactionDidChange(List<MessageReactionChange> list) { // Occurs when the reactions change. } public void OnConnected() { Debug.Log("Connected"); } public void OnTokenExpired() { // Occurs when the token has expired. } public void OnTokenWillExpire() { // Occurs when the token is about to expire } public void OnAuthFailed() { // Occurs when the user is forced to log out of the current account due to an authentication failure. } public void OnKickedByOtherDevice() { // Occurs when the user is forced to log out of the current account on the current device due to login to another device. } public void OnLoginTooManyDevice() { // Occurs when the user is forced to log out of the current account because he or she reached the maximum number of devices that the user can log in to with the current account. } public void OnChangedIMPwd() { // Occurs when the user is forced to log out of the current account because the login password has changed. } public void OnForbidByServer() { // Occurs when the current user account is banned. } public void OnRemovedFromServer() { // Occurs when the current user account is removed from the server. } public void OnLoggedOtherDevice(string deviceName, string info) { // Occurs when the user logs in to another device with the current account. } public void OnDisconnected() { Debug.Log("Disconnected"); } public void OnMessageContentChanged(Message msg, string operatorId, long operationTime) { } public void OnMessagePinChanged(string messageId, string conversationId, bool isPinned, string operatorId, long operationTime) { } public void OnLoggedOtherDevice(string str) { } public void OnAppActiveNumberReachLimitation() { } public void OnMessageContentChanged(Message msg, string operatorId, long operationTime) { } public void OnMessagePinChanged(string messageId, string conversationId, bool isPinned, string operatorId, long operationTime) { } public void OnOfflineMessageSyncStart() { } public void OnOfflineMessageSyncFinish() { }
-
-
Log in to Agora Chat
When a user presses Join, your app logs in to Agora Chat. When a user presses Leave, the app logs out of Agora Chat. To implement this logic, in the
NewBehaviourScriptclass, add the following method beforeStart:public void joinLeave() { if (isJoined) { agoraChatClient.Logout(true, callback: new CallBack( onSuccess: () => { Debug.Log("Logout succeed"); isJoined = false; GameObject.Find("joinBtn").GetComponentInChildren<TextMeshProUGUI>().text = "Join"; }, onError: (code, desc) => { Debug.Log($"Logout failed, code: {code}, desc: {desc}"); })); } else { // Use LoginWithToken to replace LoginWithAgoraToken for the SDK of v1.3.0 or later agoraChatClient.LoginWithAgoraToken(userId, token, callback: new CallBack( onSuccess: () => { Debug.Log("Login succeed"); isJoined = true; GameObject.Find("joinBtn").GetComponentInChildren<TextMeshProUGUI>().text = "Leave"; }, onError: (code, desc) => { Debug.Log($"Login failed, code: {code}, desc: {desc}"); })); } } -
Send a message
To send a message to Agora Chat when a user presses the >> button, add the following method to the
NewBehaviourScriptclass, beforeStart:public void sendMessage() { string recipient = GameObject.Find("userName").GetComponent<TMP_InputField>().text; string Msg = GameObject.Find("message").GetComponent<TMP_InputField>().text; if (Msg == "" || recipient == "") { Debug.Log("You did not type your message"); return; } Message msg = Message.CreateTextSendMessage(recipient, Msg); displayMessage(Msg, true); agoraChatClient.ChatManager.SendMessage(ref msg, new CallBack( onSuccess: () => { Debug.Log($"Send message succeed"); GameObject.Find("message").GetComponent<TMP_InputField>().text = ""; }, onError: (code, desc) => { Debug.Log($"Send message failed, code: {code}, desc: {desc}"); })); } -
Display chat messages
To display sent and received messages in your app, add the following method to the
NewBehaviourScriptclass:public void displayMessage(string messageText, bool isSentMessage) { if (isSentMessage) { messageList.text += "<align=\"right\"><color=black><mark=#dcf8c655 padding=\"10, 10, 0, 0\">" + messageText + "</color></mark>\n"; } else { messageList.text += "<align=\"left\"><color=black><mark=#ffffff55 padding=\"10, 10, 0, 0\">" + messageText + "</color></mark>\n"; } } -
Clean up the resources
When you quit the app, it calls
OnApplicationQuit. You use this method for clean up. To Implement the clean up logic, in theNewBehaviourScriptclass, add the following afterStart:void OnApplicationQuit() { agoraChatClient.ChatManager.RemoveChatManagerDelegate(this); agoraChatClient.Logout(true, callback: new CallBack( onSuccess: () => { Debug.Log("Logout succeed"); }, onError: (code, desc) => { Debug.Log($"Logout failed, code: {code}, desc: {desc}"); })); }
Test your implementation
To ensure that you have implemented Peer-to-Peer Messaging in your app:
-
In the
NewBehaviourScriptclass, updateuserId,token, andappIdwith values from Agora Console. To get your App ID, see Get Chat project information. -
In Unity Editor, click Play. A moment later you see the project installed on your development device.
-
Click Join to log in to Agora Chat.
-
Type the recipient user name in the Recepient Name field.
-
Type a message in the Message field and press
>>.The message is sent and a confirmation message is displayed in the debug console.
-
Register the recipient user in Agora Console and Generate a user token.
-
In the
NewBehaviourScriptclass, updateuserIdandtokenwith values you generated for recipient. Make sure you use the sameappIdas for both users. -
Save your changes and click Play to run the app.
-
Click Join to log in to the Chat.
You see a message in the scroll view that you sent earlier.
Reference
This section contains content that completes the information in this page, or points you to documentation that explains other aspects to this product.
- For more code samples, see Samples and demos.
Next steps
In a production environment, best practice is to deploy your own token server. Users retrieve a token from the token server to log in to Chat. To see how to implement a server that generates and serves tokens on request, see Secure authentication with tokens.
