Web

Updated at:

This topic describes how to integrate the Real-Time Messaging (RTM) feature for web applications.

Introduction

Real-Time Messaging provides low latency, high concurrency, and high reliability. It is ideal for scenarios such as live chat interactions and voice chat rooms.

Concepts

Session: A real-time messaging session is uniquely identified by a sessionId. A session supports join, leave, and close operations. You must create and join a session before sending or receiving real-time messages. With DingRTC, you can create multiple sessions with different sessionIds. These sessions do not interfere with each other.

Broadcast message: A message sent to all other members in a session.

Peer-to-peer message: A message sent to a specific user in a session, identified by their UserID.

Integration methods

The Web RTM software development kit (SDK) supports two integration methods:

  • Standalone: You can join a channel using the RTM instance. This method is suitable if you only use RTM.

  • With DingRTC: You can share the channel connection with a DingRTC instance. This method is suitable if you use both DingRTC and RTM.

The following integration examples use ES6 syntax:

  1. Obtain an RTM instance and join a channel:

    // Standalone use
    import RTM from '@dingrtc/rtm';
    
    const rtm = new RTM();
    // Activate the DingRTC service. For more information, see https://help.aliyun.com/document_detail/2640080.html.
    // Get user configuration to join the channel.
    await rtm.join({
      appId: '',
      userName: '',
      channel: '',
      uid: '',
      token: ''
    });
    
    // Use with DingRTC
    import DingRTC from 'dingrtc';
    import RTM from '@dingrtc/rtm';
    
    const client = DingRTC.createClient();
    
    const rtm = new RTM();
    // RTM and RTC share the same channel connection.
    client.register(rtm);
    
    await client.join({
      appId: '',
      userName: '',
      channel: '',
      uid: '',
      token: '',
    });
  2. Set callback listeners for the RTM instance:

    // Listen for this event only in standalone mode. This is not required when used with DingRTC.
    rtm.on('connection-state-changed', (currState, prevState, reason) => {
      console.log(currState, prevState, reason)
    })
    rtm.on('message', (data) => {
      console.log(data)
    })
    // Listen for session add/remove events.
    rtm.on('session-add', (session) => {
      console.log(session)
    })
    rtm.on('session-remove', (session) => {
      console.log(session)
    })
    // Listen for events when session members join or leave.
    rtm.on('session-user-join', (sessionId, uid) => {
      console.log(sessionId, uid)
    })
    rtm.on('session-user-left', (sessionId, uid) => {
      console.log(sessionId, uid)
    })
  3. The session initiator creates and joins a session:

    await rtm.joinSession(sessionId); // If the session does not exist, calling joinSession creates and then joins the session.
  4. Other members in the channel receive a session-add event notification and then join the same session:

    await rtm.joinSession(sessionId); // If the session exists, calling joinSession directly joins the session.
  5. You receive a session-user-join event notification when you join a session with existing members or when new members join. To send peer-to-peer real-time messages, you must maintain the session member list at the application layer:

    // Listen for events when session members join or leave.
    rtm.on('session-user-join', (sessionId, uid) => {
        // The addSessionUser method is implemented by the application layer to add new users to the session.
        addSessionUser(sessionId, uid);
    })

    When other members leave the session, you receive a session-user-left event notification. You can maintain the session member list as needed:

    rtm.on('session-user-left', (sessionId, uid) => {
      // The removeSessionUser method is implemented by the application layer to remove users who have left the session.
      removeSessionUser(sessionId, uid);
    })
  6. The SDK supports sending and receiving UTF-8 encoded strings and binary data. For web applications, you can use a Uint8Array array to pass messages as a parameter. The current limit is 60 messages per second. A single message must not exceed 4 KB. Longer messages may be lost.

    Send a broadcast message:

    const message = 'hello world';
    const encoder = new TextEncoder();
    const sessionId = 'xxxxxx';
    // Broadcast
    rtm.publish(sessionId, encoder.encode(message));

    Send a peer-to-peer message:

    const message = 'hello world';
    const encoder = new TextEncoder();
    // Peer-to-peer publish. Both users must be in the same RTM session.
    const otherUserId = 'user1';
    const sessionId = 'xxxxxx';
    rtm.publish(sessionId, encoder.encode(message), otherUserId);

    Receive a message:

    // Listen for remote message publish events.
    rtm.on('message', (data) => {
      const {
        message, // Message payload in Uint8Array format
        uid, // UID of the publisher
        sessionId, // sessionId to which the message belongs
        broadcast, // Indicates if the message is a broadcast or peer-to-peer
      } = data;
      console.log(decoder.decode(message))
    })
  7. If the local client no longer needs the real-time messaging feature, you can leave the session:

    rtm.leaveSession(sessionId);

    After you leave a session, you will no longer receive broadcast messages from other members in that session, and they will not be able to send peer-to-peer messages to you.

  8. If a session is no longer needed, you can close the session:

    rtm.closeSession(sessionId);

    When a session is closed, all members, including the one who initiated the closure, receive a session-remove event notification. The session then becomes unavailable.

Additionally, when you leave the channel, the SDK clears all session information internally, and the real-time messaging feature becomes unavailable.