Suggestions

close search

Add Messaging, Voice, and Authentication to your apps with Vonage Communications APIs

Visit the Vonage API Developer Portal

Back to Tutorials

Set up a Basic Windows Client

This tutorial will walk you through the steps of setting up a basic Windows client that uses the Vonage Video API.

Overview

All applications that use the Vonage Video API require both a client and a server component. The client-side code is what loads in an end-user’s Windows app and handles the majority of OpenTok functionality, including connecting to the session, publishing audio-video streams to the session, and subscribing to other clients’ streams. For more information on clients, servers, and sessions, see OpenTok Basics.

In this tutorial, you will be utilizing the OpenTok Windows SDK, OpenTok's client-side library for Windows, to quickly and easily build a real-time interactive video application.

Here are the items that will be covered in this tutorial:


Estimated completion time: 25 mins

Want to skip this tutorial? You can jump to the completed Windows client code in the Basic-Video-Chat folder of our Windows sample app repo on GitHub. The repo includes a README with documentation for running and exploring the code.

Requirements

To complete this tutorial, you’ll need:

Step 1: Creating a new project

  1. Open Visual Studio and select New > Project from the File menu.
  2. In the New Project dialog box, select Windows > WPF Application (Visual C#), give a name for the application, and then click the OK button.

Step 2: Adding the OpenTok Windows SDK

Use NuGet to load the OpenTok Windows SDK, using one of the following methods:

Add the OpenTok Windows classes to the application — in Visual Studio, open the MainWindow.xaml.cs file. And add the following statements:

using OpenTok;

This imports the classes of the OpenTok Windows SDK that the app will use.

Step 3: Setting up authentication

In order to connect to an OpenTok session, the client will need access to some authentication credentials — an API key, session ID, and token. In a production application, these credentials should be generated by a server, but to speed things up we will just hard code the values for now:

  1. In the MainWindow class, add some static variables to store the API key, session ID, and token. We'll also add some constants for our log message identifier and permissions:

    public partial class MainWindow : Window
        {
            public const string API_KEY = "";
            public const string SESSION_ID = "";
            public const string TOKEN = "";
    
  2. Adjust the code by hard coding the values for the API_KEY, SESSION_ID and TOKEN.

    To do this, log into your Video API account, either create a new OpenTok API project or use an existing OpenTok API project, then go to your project page and scroll down to the Project Tools section. From there, you can generate a session ID and token manually. Use the project’s API key along with the session ID and token you generated.

Important: You can continue to get the session ID and token values from your Account during testing and development, but before you go into production you must set up a server. We will discuss this in Next steps at the end of this tutorial.

For more information on sessions, tokens, and servers, check out Video API Basics.

Step 4: Connecting to the session

Next, we will connect to the OpenTok session. You must do this before you can publish your audio-video stream to the session or view other participants streams.

  1. Add a Session member variable to the MainWindow class (right after the last line you added in Step 3):

    Session Session;

    The Session class is defined in the OpenTok Windows SDK. It represents an OpenTok session and includes methods for interacting with the session.

  2. In the MainWindow() constructor function, add the following lines, after the InitializeComponent() method:

    Session = new Session(Context.Instance, API_KEY, SESSION_ID);
    
      Session.Connected += Session_Connected;
      Session.Disconnected += Session_Disconnected;
      Session.Error += Session_Error;
      Session.StreamReceived += Session_StreamReceived;
    
      Session.Connect(TOKEN);
      

    This code uses the Session() constructor to instantiate a Session object. The constructor takes three parameters:

    • The Windows context associated with this application
    • The OpenTok session ID
    • The token

    The next lines add event handlers for session-related events. (We will implement these in the next steps).

    The Session.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 one parameter: the authentication token for this client to connect to the OpenTok session.

  3. Next we will implement methods of the SessionListener interface. Add the following code to the end of the MainWindow class (before the closing bracket of the class):

    private void Session_Connected(object sender, EventArgs e)
    {
      Console.WriteLine("Connected to session.");
    }
    
    private void Session_Disconnected(object sender, EventArgs e)
    {
        Console.WriteLine("Disconnected from session.");
    }
    
    private void Session_Error(object sender, Session.ErrorEventArgs e)
    {
      Console.WriteLine("Session error:" + e.ErrorCode);
    }
    
    private void Session_StreamReceived(object sender, Session.StreamEventArgs e)
    {
      Console.WriteLine("Stream received in session.");
    }
      
    • When the client connects to the OpenTok session, the Session.Connected event is raised (and the Session_Connected() event handler is called).

    • When the client disconnects from the OpenTok session, the Session.Disconnected event is sent (and the Session_Disconnected() method is called).

    • If the client fails to connect to the OpenTok session, the Session.Error event is sent (and the Session_Error() method is called).

    • When another client publishes a stream to the OpenTok session, the Session.StreamReceived event is raised (and the Session_StreamReceived() event handler is called).

    For now, the app writes to the debugger console when any of these events occur.

Debug your application. If the app successfully connects to the OpenTok session, the Session_Connected() method logs to the debug console.

Step 5: Adjusting the sample app UI

By default, the OpenTok Windows SDK renders videos you publish and subscribe to using the the VideoRenderer class (defined in the OpenTok Windows SDK). This class renders videos to an Windows Presentation Framework control.

For this sample app, define the target controls in the application's MainWindow.xaml file. In Visual Studio, open that file and edit its XML to add a reference to the OpenTok namespace and to add two VideoRenderer objects to the main Grid control of the application:

<Window x:Class="BasicVideoChat.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BasicVideoChat"
        xmlns:OpenTok="clr-namespace:OpenTok;assembly=WPFVideoRenderer"
        mc:Ignorable="d"
        Title="MainWindow" Height="960" Width="640">
    <Grid>
        <OpenTok:VideoRenderer x:Name="PublisherVideo" HorizontalAlignment="Center" Height="480" VerticalAlignment="Top" Width="640">
        </OpenTok:VideoRenderer>
        <OpenTok:VideoRenderer x:Name="SubscriberVideo" HorizontalAlignment="Center" Height="480" VerticalAlignment="Bottom" Width="640">
        </OpenTok:VideoRenderer>
    </Grid>
</Window>

Step 6: Publishing a stream to the session

When the app connects to the OpenTok session, we want it to publish an audio-video stream to the session, using the camera and microphone:

  1. Add a Publisher member variable to the MainWindow class (after the declaration of the Session member variable):

    Publisher Publisher;
    

    The Publisher class is defined in the OpenTok Windows SDK.

  2. Modify the MainWindow() constructor to include code to initialize a video capturer for the publisher and use that video capturer in a Publisher object:

    Publisher = new Publisher(Context.Instance, renderer: PublisherVideo);
    

    The code uses the Publisher() constructor to instantiate a Publisher object. Two parameters are passed into the constructor: the Windows application context and the video renderer (defined in the MainApplication.xaml file).

  3. Modify the Session_Connected() method to include code to publish a stream to the session:

    private void Session_Connected(object sender, System.EventArgs e)
    {
        Session.Publish(Publisher);
    }
    

    When the application connects to the session (and the SessionConnected event is raised) the Session_Connected event handler calls the Session.Publish() method, passing in the Publisher object. This causes the app to publish an audio-video stream to the OpenTok session, using the video capturer's microphone and camera as the audio source and video source.

Debug your application. The app displays the local video preview of the publisher and, when the app successfully connects to the OpenTok session, it publishes a stream to the session.

Note: This application uses the default video capturer, which uses the system's default camera and microphone as the video and audio source for the published stream.You can implement custom video capturer and video renderers by creating classes that implement the IVideoCapturer and IVideoRenderer interfaces, defined in the OpenTok Windows SDK. For sample code, see the CustomVideoRenderer and ScreenSharing sample applications in the opentok-windows-sdk-samples repo on GitHub.

Step 7: Subscribing to other client streams

We want clients to be able to subscribe to (or view) other clients’ streams in the session:

When another client publishes a stream to a session, the Session.StreamReceived message is sent and this method is called. A Stream object, defined in the OpenTok Windows SDK, is passed into the event handler. It represents an audio-video stream in the OpenTok session.

The code initializes an instance of the Subscriber class, defined in the OpenTok Windows SDK. The Subscriber class defines an object that a client uses to subscribe to (view) streams published by other clients.

The Subscriber() constructor takes three parameters:

Step 8: Running the app and creating an installer

To add a second stream to the session (which will display as a subscriber in your emulator), either run the app a second time in another Windows device or use the OpenTok Playground to connect to the session in a supported web browser by following the steps below:

  1. Go to OpenTok Playground (must be logged into your Account)

  2. Select the Join existing session tab

  3. Copy the session ID you used in your ViewController.m file and paste it in Session ID input field

  4. Click Join Session

  5. On the next screen, click Connect, then click Publish Stream

  6. You can adjust the Publisher options (not required), then click Continue to connect and begin publishing and subscribing

At this point you should see the stream being published from your webcam as well as the stream being published by the emulator. Returning to the emulator, you should also see the new publisher displayed on the emulated screen.

When creating an installer for your application, add Visual C++ Redistributable for Visual Studio 2015 as an installer package. Use the x86 version, the x64 version, or both, depending on the architecture of your application.

Congratulations! You've finished the 'Set up a Basic Windows Client' tutorial.
You can continue to play with and adjust the code you've developed here for the client-side of your application, but keep in mind that you'll need to implement the server component of your application before going to production (see Setting up your server below).

You can view a completed version of this sample app in the BasicVideoChat folder of the opentok-windows-sdk-samples repo on GitHub. This completed version adds code to load the session ID, token, and API key from a web service (instead of using hard-coded values).

Setting up your server

In the tutorial above, we had you hard code your authentication credentials. However, for a production application, the sessionId and token values in your code must be generated by your app server and passed to the client. Here are a couple of reasons why you don't want hard coded credentials in your production app:

You can continue testing your application with hard coded values, but when you're ready to set up a server there are a number of ways to do so:

Server Option 1 — Launch a simple REST server on Heroku with one click

This is probably the fastest way to get a server up and running, but it has limited functionality. Simply click the Heroku button below, at which point you'll be sent to Heroku's website and prompted for your OpenTok API Key and API Secret — you can get these values on your project page in your Video API account. If you don't have a Heroku account, you'll need to sign up (it's free).

Deploy

Want to explore the code? The button above launches server code from the learning-opentok-php GitHub repo. Visit the repo to review the code as well as additional documentation — you can even fork the repo and make changes before deploying.

Prefer Node.js? Visit the learning-opentok-node repo for the same functionality using Node.js (including a Heroku deploy button).

Once the server is deployed on Heroku, you'll need to add some code to your project to fetch the credentials from the server. The code should make an HTTP GET request to https://YOURAPPNAME.herokuapp.com/session. The body of the response is JSON that includes properties defining the OpenTok API key, the session ID and a token:


{
    "apiKey": "8675309",
    "sessionId": "2_MX20NTMyODc3Mn5...",
    "token": "T1==cGFydG5lcl5NTMyOD..."
}

Server Option 2 — Build from scratch using the server SDKs

Option 1 uses REST endpoints for transmitting credentials to the client, but that's only one of many ways to implement a server with OpenTok. If you want a greater level of customization, you can review OpenTok's Server SDK documentation for the server-side language of your choice (available for PHP, Node.js, Java, .NET, Python and Ruby). The documentation goes over the setup process and the various methods you'll need to generate sessions and tokens, as well as other server-side functionality.