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

  1. Clients retrieve an authentication token from your app server.
  2. Users log in to Chat using the App ID, 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 the Agora Chat server.
    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. Use VITE to create a new project. If VITE is not installed, run npm i vite -g to install it. Then, run npm create vite@latest agora_quickstart. In this example, we choose "React + JavaScript" to create the project.

The project directory now has the following structure:

agora_quickstart
├─ index.html
├─ main.js
└─ package.json
  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"
         }
     }

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.

Copy the following code to the App.jsx file to implement the UI:

import { useEffect, useState, useRef } from "react";
import "./App.css";
import AgoraChat from "agora-chat";

function App() {
  // Replaces <Your App ID> with your App ID.
  const appId = "<Your App ID>";
  const [userId, setUserId] = useState("");
  const [token, setToken] = useState("");
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [peerId, setPeerId] = useState("");
  const [message, setMessage] = useState("");
  const [logs, setLogs] = useState([]);
  const chatClient = useRef(null);

  // Logs into Agora Chat.
  const handleLogin = () => {
    if (userId && token) {
      chatClient.current.open({
        user: userId,
        // Use agoraToken for v1.2.1 and earlier, but accessToken for 1.2.2 and later.
        accessToken: token,
      });
    } else {
      addLog("Please enter userId and token");
    }
  };

  // Logs out.
  const handleLogout = () => {
    chatClient.current.close();
    setIsLoggedIn(false);
    setUserId("");
    setToken("");
    setPeerId("");
  };

  // Sends a peer-to-peer message.
  const handleSendMessage = async () => {
    if (message.trim()) {
      try {
        const options = {
          chatType: "singleChat", // Sets the chat type as a one-to-one chat.
          type: "txt", // Sets the message type.
          to: peerId, // Sets the recipient of the message with user ID.
          msg: message, // Sets the message content.
        };
        let msg = AgoraChat.message.create(options);

        await chatClient.current.send(msg);
        addLog(`Message send to ${peerId}: ${message}`);
        setMessage("");
      } catch (error) {
        addLog(`Message send failed: ${error.message}`);
      }
    } else {
      addLog("Please enter message content");
    }
  };

  // Add log.
  const addLog = (log) => {
    setLogs((prevLogs) => [...prevLogs, log]);
  };

  useEffect(() => {
    // Initializes the Web client.
    chatClient.current = new AgoraChat.connection({
      appId: appId,
    });

    // Adds the event handler.
    chatClient.current.addEventHandler("connection&message", {
      // Occurs when the app is connected to Agora Chat.
      onConnected: () => {
        setIsLoggedIn(true);
        addLog(`User ${userId} Connect success !`);
      },
      // Occurs when the app is disconnected from Agora Chat.
      onDisconnected: () => {
        setIsLoggedIn(false);
        addLog(`User Logout!`);
      },
      // Occurs when a text message is received.
      onTextMessage: (message) => {
        addLog(`${message.from}: ${message.msg}`);
      },
      // Occurs when the token is about to expire.
      onTokenWillExpire: () => {
        addLog("Token is about to expire");
      },
      // Occurs when the token has expired.
      onTokenExpired: () => {
        addLog("Token has expired");
      },
      onError: (error) => {
        addLog(`on error: ${error.message}`);
      },
    });
  }, []);

  return (
    <>
      <div
        style={{
          width: "500px",
          display: "flex",
          gap: "10px",
          flexDirection: "column",
        }}
      >
        <h2>Agora Chat Examples</h2>
        {!isLoggedIn ? (
          <>
            <div>
              <label>UserID: </label>
              <input
                type="text"
                value={userId}
                onChange={(e) => setUserId(e.target.value)}
                placeholder="Enter the user ID"
              />
            </div>
            <div>
              <label>Token: </label>
              <input
                type="text"
                value={token}
                onChange={(e) => setToken(e.target.value)}
                placeholder="Enter the token"
              />
            </div>
            <button onClick={handleLogin}>Login</button>
          </>
        ) : (
          <>
            <h3>Welcome, {userId}</h3>
            <button onClick={handleLogout}>Logout</button>
            <div>
              <label>Peer userID: </label>
              <input
                type="text"
                value={peerId}
                onChange={(e) => setPeerId(e.target.value)}
                placeholder="Enter the peer user ID"
              />
            </div>
            <div>
              <label>Peer message: </label>
              <input
                type="text"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                placeholder="Input message"
              />
              <button onClick={handleSendMessage}>Send</button>
            </div>
          </>
        )}

        <h3>Operation log</h3>
        <div
          style={{
            height: "300px",
            overflowY: "auto",
            border: "1px solid #ccc",
            padding: "10px",
            textAlign: "left",
          }}
        >
          {logs.map((log, index) => (
            <div key={index}>{log}</div>
          ))}
        </div>
      </div>
    </>
  );
}

export default App;

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
$ npm run dev

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.