Joining a Session

In this guide you will learn to connect your application to a video session.

Prerequisite

You will need a valid Vonage Video API account, if you don't have one you can sign up for a free trial.

You should also ensure that you have created a session and generated a token for all users involved.

Initializing a Session object

Before you can connect to a session, you will need to instantiate a session object using any of the client SDKs available.

Instantiate a Session object by calling the OT.initSession() method with your application ID and the appropriate session ID:

// Replace with your application ID and session ID:
var session = OT.initSession(applicationId, sessionId);

The OT.initSession() method returns a Session object, through which subsequent API calls take place.

Note that calling the OT.initSession() method does not create a session; it creates a JavaScript Session object, which represents an existing session. You can create a session using the server-side SDK. See Creating a session.

If the user's browser does not support WebRTC, the call to OT.initSession() results in the page displaying a message to the user. To check for WebRTC support and prevent this message from being displayed, you can call the OT.checkSystemRequirements() method before calling OT.initSession():

if (OT.checkSystemRequirements() == 1) {
  var session = OT.initSession(applicationId, sessionId);
} else {
  // The client does not support WebRTC.
  // You can display your own message.
}

Connecting to a session

Once you have a session ID, and initialized a session object using it, the next step is to connect to the session.

Learn how to connect to sessions below by selecting your platform/language of choice:

When you add an OTSession component it automatically connects to the Vonage Video API session.

<OTSession
  applicationId="your-application-ID"
  sessionId="your-session-id"
  token="your-session-token"
>
  <OTPublisher/>
  <OTSubscriber/>
</OTSession>

Replace your-application-ID, your-session-id, and your-session-token with your API key, a session ID, and a token for the session.

Note that you add the OTPublisher and OTSubscriber components and children of the OTSession component.

You can pass an error and sessionConnected event handlers in the OTSession component. The error event handler is called if the client fails to connect to the session. And the sessionConnected event handler is called when the client connects to the session:

<OTSession
  applicationId="your-application-ID"
  sessionId="your-session-id"
  token="your-session-token"
  eventHandlers={{
    error: event => {
        console.log('error', event);
      },
    sessionConnected: event => {
      console.log('session connected', event);
    },
  }}
>
  <OTPublisher style={{ width: 100, height: 100 }}/>
  <OTSubscriber style={{ width: 100, height: 100 }} />
</OTSession>

Disconnect from a Session

Learn how to disconnect a user from a session.

The client disconnects from the session when you unmount the OTSession component.

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}
>
    {/* ... */}

Detecting when you have disconnected

You setup an EventListner to execute a function if a user is disconnected from a session.

For example, the function can notify the user whenever they loose connection and are no longer connected to the session.

When your client disconnects from a session, the OTSession component dispatches a sessionDisconnected event:

<OTSession
  applicationId="your-api-key"
  sessionId="your-session-id"
  token="your-session-token"
  eventHandlers={{
    sessionDisconnected: event => {
        console.log('disconnected', event);
      },
    connected: event => {
      console.log('subscriber connected', event);
    },
  }}
>
  <OTPublisher style={{ width: 100, height: 100 }}/>
  <OTSubscriber style={{ width: 100, height: 100 }} />
</OTSession>

Automatic reconnection

Clients will attempt to automatically reconnect to a session they disconnect unexpectedly (for example, due to a drop in network connectivity).

You do not need to add any code to have the clients reconnect automatically, unless you want to respond to events dispatched when your client disconnects and reconnects.

Clients will attempt to automatically reconnect to a session they disconnect unexpectedly (for example, due to a drop in network connectivity). You do not need to add any code to have the clients reconnect automatically, unless you want to respond to events dispatched when your client disconnects and reconnects.

When the connection is dropped and the client tries to reconnect, the OTSession object dispatches a sessionReconnecting event. When the connection is restored, the Session object dispatches a sessionReconnected. If the client cannot restore the connection, the client disconnects from the session, and the Session object dispatches the sessionDisconnected.

In response to these events, your application can (optionally) display user interface notifications indicating the temporary disconnection, reconnection, and disconnection states:

<OTSession
  applicationId={this.apiKey}
  sessionId={this.sessionId}
  token={this.token}
  eventHandlers={{
    sessionReconnecting: event => {
      // Display a user interface notification.
    },
    sessionReconnected: event => {
      // Adjust user interface.
    },
    sessionDisconnected: event => {
      // Adjust user interface.
    },
  }
>
    {/* ... */}

When your client temporarily disconnects from a session, the Subscriber objects in clients subscribing to a stream you publish dispatch events when your published stream drops and when (and if) it resumes automatically. For more information, see Automatic reconnection.

Troubleshooting session connection issues (JavaScript)

The Session.connect() method has a callback function which is passed an optional error parameter. If this parameter is present and defined (not null or undefined), then there was an error when connecting. Looking for this error in your code will help you decipher why the end-user was unable to connect:

session.connect(token, function(err) {
  if (err) {
    // handle error
  } else {
    // connection succeeded
  }
});

A large number of errors that come back when attempting to connect are due to either invalid or expired tokens.

Another common reason for connecting to a session failing is due to the end user's internet connection. Examples of this include:

  • The end user has lost their internet connection
  • The end user has common ports blocked because they're on a restrictive network.

This will result in an error with the code 1006. We recommend you handle this using the code below. Other reasons for connecting to a session failing include the Vonage video servers being down, or that some kind of unexpected error happened (such as a 500-level error in the server). While this doesn't happen often, it is good practice to handle these errors.

If you follow these instructions your error handling code should look something like:

session.connect(token, function(err) {
  if (err) {
    if (err.name === "OT_NOT_CONNECTED") {
      showMessage('Failed to connect. Please check your connection and try connecting again.');
    } else {
      showMessage('An unknown error occurred connecting. Please try again later.');
    }
  }
});

You can lose your connection after you have already successfully connected to a Session. You can handle this case by listening for the sessionDisconnected event with a reason of "networkDisconnected":

session.on({
  sessionDisconnected: function(event) {
    if (event.reason === 'networkDisconnected') {
      showMessage('You lost your internet connection.'
        + 'Please check your connection and try connecting again.');
    }
  }
});

Troubleshooting session connection issues (React Native)

A large number of errors that come back when attempting to connect are due to either invalid or expired tokens. Make sure you are following the token best practices outlined here.

Another common reason for connecting to a session failing is due to the end user's internet connection. Examples of this include:

  • The end user has lost their internet connection
  • The end user has common ports blocked because they're on a restrictive network.