Suggestions

close search

Back to Basic Video Chat Overview

Basic Video Chat Step 4: Connecting to the session

  1. 1
    Basic Video Chat Step 1:
    Setting up the test web service
  2. 2
    Basic Video Chat Step 2:
    Configuring and testing the app
  3. 3
    Basic Video Chat Step 3:
    Initializing an OpenTok session
  4. 4
    Basic Video Chat Step 4:
    Connecting to the session
  5. 5
    Basic Video Chat Step 5:
    Publishing a stream to the session
  6. 6
    Basic Video Chat Step 6:
    Subscribing to audio-video streams

Upon obtaining the session ID, token, and API, the app calls the initializeSession() method. First, this method initializes a Session object:

// Initialize Session Object
var session = OT.initSession(apiKey, sessionId);

The OT.initSession() method takes two parameters — the OpenTok API key and the session ID. It initializes and returns an OpenTok Session object.

The connect() method of the Session object connects the client application to the OpenTok session. You must connect before sending or receiving audio-video streams in the session (or before interacting with the session in any way). The connect() method takes two parameters — a token and a completion handler function:

// Connect to the Session
session.connect(token, function(error) {

  // If the connection is successful, initialize a publisher and publish to the session
  if (!error) {
    var publisherOptions = {
      insertMode: 'append',
      width: '100%',
      height: '100%'
    };
    var publisher = OT.initPublisher('publisher', publisherOptions, function(error) {
      if (error) {
        console.log('There was an error initilizing the publisher: ', error.name, error.message);
        return;
      }
      session.publish(publisher);
    });
  } else {
    console.log('There was an error connecting to the session:', error.name, error.message);
  }
});

An error object is passed into the completion handler of the Session.connect() method if the client fails to connect to the OpenTok session. Otherwise, no error object is passed in, indicating that the client connected successfully to the session.

The Session object dispatches a sessionDisconnected event when your client disconnects from the session. The application defines an event handler for this event:

session.on('sessionDisconnected', function(event) {
  console.log('You were disconnected from the session.', event.reason);
});
Got it! Go to step 5
  1. 1
    Basic Video Chat Step 1:
    Setting up the test web service
  2. 2
    Basic Video Chat Step 2:
    Configuring and testing the app
  3. 3
    Basic Video Chat Step 3:
    Initializing an OpenTok session
  4. 4
    Basic Video Chat Step 4:
    Connecting to the session
  5. 5
    Basic Video Chat Step 5:
    Publishing a stream to the session
  6. 6
    Basic Video Chat Step 6:
    Subscribing to audio-video streams