Detecting when clients have connected and disconnected

Learn how to detect when a client connects and disconnects from a session.

The OTSession object dispatches a connectionCreated event when a new client (excluding your own) connects to the session. The OTSession object dispatches a connectionDestroyed event when other clients leave the session. These events are defined by the ConnectionEvent class, which has a connection object, which is a Connection object for the connection (created or destroyed) related to the event:

let this.connectionCount = 0;
const this.sessionEventHandlers = {
  connectionCreated: function (event) {
    connectionCount++;
    if (event.connection.connectionId != session.connection.connectionId) {
      console.log('Another client connected. ' + connectionCount + ' total.');
    }
  },
  connectionDestroyed: function connectionDestroyedHandler(event) {
    connectionCount--;
    console.log('A client disconnected. ' + connectionCount + ' total.');
  }
  sessionConnected: function (event) {
    // include your own client's connection in the count
    connectionCount++;
  },
};

// reference later in JSX:

<OTSession
  applicationId={this.apiKey}
  sessionId={this.sessionId}
  token={this.token}
  eventHandlers={this.sessionEventHandlers}
>
    {/* ... */}