Skip to main content
Android
iOS
Web
Windows
Unity
Flutter
React Native

SDK quickstart

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 for Web.

Understand the tech

The following figure shows the workflow of sending and receiving peer-to-peer messages using Chat SDK.

understand

  1. Clients retrieve an authentication token from your app server.
  2. Users log in to Chat using the app key, their user ID, and token.
  3. Clients send and receive messages through Chat as follows:
    1. Client A sends a message to Client B. The message is sent to Chat.
    2. The server delivers the message to Client B. When Client B receives a message, the SDK triggers an event.
    3. 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 Windows or macOS computer that meets the following requirements:
    • A browser supported by the Agora Chat SDK:
      • Internet Explorer 9 or later
      • FireFox 10 or later
      • Chrome 54 or later
      • Safari 6 or later
    • Access to the Internet. If your network has a firewall, follow the instructions in Firewall Requirements to access Agora services.
  • Node.js and npm

Project setup

To create the environment necessary to add peer-to-peer messaging into your app, do the following:

  1. For a new web project, create a new directory and name it agora_quickstart. Navigate to this directory in terminal and run npm init. This creates a package.json file. Then, create the following files:
  • index.html, which sets the user interface of the Web app
  • main.js, which contains the code for implementing the messaging logic

The project directory now has the following structure:

agora_quickstart
├─ index.html
├─ main.js
└─ package.json
Copy
  1. Integrate the Agora Chat SDK into your project through npm. Add 'agora-chat' and 'vite' to the 'package.json' file.

    {
    "name": "agora_quickstart",
    "private": true,
    "version": "0.0.0",
    "type": "module",
    "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
    },
    "dependencies":{
    "agora-chat": "latest"
    },
    "devDependencies": {
    "vite": "^3.0.7"
    }
    }
    Copy

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

Copy the following code to the index.html file to implement the UI.

<script type="module" src="/main.js"></script> is used to refer to the main.js file.

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Agora Chat Examples</title>
<script type="module" src="/main.js"></script>
<!-- <link rel="stylesheet" href="style.css" type="text/css" /> -->
</head>

<body>
<h2>Agora Chat Examples</h2>
<form id="loginForm">
<div class="input-field">
<label>User ID</label>
<input type="text" placeholder="User ID" id="userID">
</div>
<div class="input-field">
<label>Token</label>
<input type="text" placeholder="Token" id="token">
</div>
<div>
<button type="button" id="login">Login</button>
<button type="button" id="logout">Logout</button>
</div>
<div class="input-field">
<label>Peer user ID</label>
<input type="text" placeholder="Peer user ID" id="peerId">
</div>
<div class="input-field">
<label>Peer Message</label>
<input type="text" placeholder="Peer message" id="peerMessage">
<button type="button" id="send_peer_message">send</button>
</div>
</form>
<hr/>
<div id="log"></div>
</body>

</html>
Copy

Implement the sending and receiving of messages

To enable your app to send and receive messages between individual users, do the following:

  1. Import Chat SDK . Copy the following code to the main.js file:

    // Javascript
    // Note that to avoid browser-compatibility issues, this sample uses the import command to import the SDK and the vite to package the JS file.
    import AC from 'agora-chat'
    Copy

    If you use typescript, use the following code:

    // Typescript
    import AC, { AgoraChat } from 'agora-chat'
    Copy
  2. Implement peer-to-peer messaging with the core methods provided by Chat SDK . Copy the following code and add them after the import function in the main.js file.

    // Replaces <Your app key> with your app key.
    const appKey = "<Your app key>";
    // Initializes the Web client.
    const conn = new AC.connection({
    appKey: appKey,
    });
    // Adds the event handler.
    conn.addEventHandler("connection&message", {
    // Occurs when the app is connected to Agora Chat.
    onConnected: () => {
    document
    .getElementById("log")
    .appendChild(document.createElement("div"))
    .append("Connect success !");
    },
    // Occurs when the app is disconnected from Agora Chat.
    onDisconnected: () => {
    document
    .getElementById("log")
    .appendChild(document.createElement("div"))
    .append("Logout success !");
    },
    // Occurs when a text message is received.
    onTextMessage: (message) => {
    console.log(message);
    document
    .getElementById("log")
    .appendChild(document.createElement("div"))
    .append("Message from: " + message.from + " Message: " + message.msg);
    },
    // Occurs when the token is about to expire.
    onTokenWillExpire: (params) => {
    document
    .getElementById("log")
    .appendChild(document.createElement("div"))
    .append("Token is about to expire");
    },
    // Occurs when the token has expired.
    onTokenExpired: (params) => {
    document
    .getElementById("log")
    .appendChild(document.createElement("div"))
    .append("The token has expired");
    },
    onError: (error) => {
    console.log("on error", error);
    },
    });

    // Defines the functions of the buttons.
    window.onload = function () {
    // Logs into Agora Chat.
    document.getElementById("login").onclick = function () {
    document
    .getElementById("log")
    .appendChild(document.createElement("div"))
    .append("Logging in...");
    const userId = document.getElementById("userID").value.toString();
    const token = document.getElementById("token").value.toString();
    conn.open({
    user: userId,
    agoraToken: token,
    });
    };
    // Logs out.
    document.getElementById("logout").onclick = function () {
    conn.close();
    document
    .getElementById("log")
    .appendChild(document.createElement("div"))
    .append("logout");
    };
    // Sends a peer-to-peer message.
    document.getElementById("send_peer_message").onclick = function () {
    let peerId = document.getElementById("peerId").value.toString();
    let peerMessage = document.getElementById("peerMessage").value.toString();
    let option = {
    chatType: "singleChat", // Sets the chat type as single chat.
    type: "txt", // Sets the message type.
    to: peerId, // Sets the recipient of the message with user ID.
    msg: peerMessage, // Sets the message content.
    };
    let msg = AC.message.create(option);
    conn
    .send(msg)
    .then((res) => {
    console.log("send private text success");
    document
    .getElementById("log")
    .appendChild(document.createElement("div"))
    .append("Message send to: " + peerId + " Message: " + peerMessage);
    })
    .catch(() => {
    console.log("send private text fail");
    });
    };
    };
    Copy

Test your implementation

To ensure that you have implemented Peer-to-Peer Messaging in your app:

Use vite to build the project. You can run below commands to run the project.

$ npm install
Copy
$ npm run dev
Copy

The following page opens in your browser:

To validate the peer-to-peer messaging you have just integrated into your Web app using Agora Chat:

  1. Log in
    Fill in the user ID of the sender (Leo) in the user id box and agora token in the token box, and click Login to log in to the app.

  2. Send a message
    Fill in the user ID of the receiver (Roy) in the single chat id box and type in the message ("Hi, how are you doing?") to send in the message content box, and click Send to send the message.

  3. Log out
    Click Logout to log out of the app.

  4. Receive the message
    Open the same page in a new window, log in as the receiver (Roy) and receive the message ("Hi, how are you doing?") sent from Leo.

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 details:

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.

vundefined