Skip to content

Instantly share code, notes, and snippets.

@hbaqai
Last active December 29, 2015 14:28
Show Gist options
  • Save hbaqai/7683830 to your computer and use it in GitHub Desktop.
Save hbaqai/7683830 to your computer and use it in GitHub Desktop.
Step 2 - JS Writeup
Now that you've read through (link step1), you should have a conceptual understanding of how Opentok works. In this step we'll use that knowledge to set up a web page with live video chat.
We recommend that you follow tutorial step by step, entering code snippets as you go, but if you just want the end results you can find them at our github repo: (link github repo). You'll still need to have at least a web server set up. If you don't know how to do that you should at least read the following section.
SETTING UP A WEB SERVER
Before starting, you'll need to make sure you have a web server available. You can use a popular one like (link Apache) or (link Nginx), or if you wanted something quick and easy way would be to start one with python (Mac and Linux users typically have this preinstalled, Windows users click here). Once you have python running, open a terminal, get to a new empty directory, and type in the following line:
python -m SimpleHTTPServer 8000`
Any files placed here will be served at the address http://localhost:8000/ in your web browser.
If you try to run your WebRTC enabled page directly from the file system, you'll receive an error regarding browser permissions.
LAYOUT
Next, open your favorite text editor and enter the skeleton of an html page, as shown below:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
</body>
</html>
From here you'll need to import Tokbox's Javascript API inside the <head> tags, as well as an open <script> tag to insert the meat of our code
<head>
<script src="http://static.opentok.com/webrtc/v2.2/js/TB.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
</script>
</head>
make sure you save the file in the root directory of your web server, and that it has a .html extension. To make sure that everything is working at this point, enter the following two lines within the <script> tags:
<script type="text/javascript" charset="utf-8">
console.log(window.location.href.indexOf("http"));
console.log("TB object: " + TB);
</script>
INITIALIZATION
With everything in place, we now need to initialize the foundation of all video conferences, our Session object, along with any handlers for events that we want to listen to. We initialize the Session to the session variable as follows:
var session = TB.initSession(38169452,"2_MX4zODE2OTQ1Mn5-V2VkIE5vdiAxMyAyMDo1MzozNCBQU1QgMjAxM34wLjkyOTI2MjE2fg");
where the parameters are the API key and Token obtained from the (link dashboard).
From here, we'll want to initialize three different handlers, the "exception" handler, the "sessionConnected" handler, and the "streamCreated" handler: This is done using TB.on() or session.on() for session events. The first parameter is the handler name as found in the TB.min.js file you imported. The second parameter is the name of the callback function for that I will implement. I recommend using meaningful callback function names such as the name of the handler along with the word "Handler" concatenated to it.
TB.on("exception", exceptionHandler);
session.on("sessionConnected", sessionConnectedHandler);
session.on("streamCreated", streamCreatedHandler);
Lets also write the functions for the callbacks now, so we have method stubs that we can fill in later.
//implement event handlers
function sessionConnectedHandler(event) {
//implementation stub
}
function streamCreatedHandler(event) {
//implementation stub
}
function exceptionHandler(event) {
//implementation stub
}
IMPLEMENTATION
With everything initialized, call the session.connect function. We'll place this right before the handler implementations for the sake of organizing between the main flow of our code and asynchronous calls:
session.connect("T1==cGFydG5lcl9pZD0zODE2OTQ1MiZzZGtfdmVyc2lvbj10YnJ1YnktdGJyYi12MC45MS4yMDExLTAyLTE3JnNpZz05ZTg3YTE1ZGEyNzFkODMzNjVkYmMzNWUxN2VjYjQwYWQ5NTNkNGNhOnJvbGU9cHVibGlzaGVyJnNlc3Npb25faWQ9Ml9NWDR6T0RFMk9UUTFNbjUtVjJWa0lFNXZkaUF4TXlBeU1EbzFNem96TkNCUVUxUWdNakF4TTM0d0xqa3lPVEkyTWpFMmZnJmNyZWF0ZV90aW1lPTEzODQ0MDQ4NTEmbm9uY2U9MC40MDk4MjE4MDUwMzQ0MzEmZXhwaXJlX3RpbWU9MTM4OTc2MTY0OSZjb25uZWN0aW9uX2RhdGE9");
Because Tokens are the authentication to enter a Session, you'll need to be sure that the Token you generated is for the corresponding Session ID in TB.initSession.
Once the session has connected, a sessionConnected event will fire, and code inside our sessionConnectedHandler will execute. So what should we do in the handler? The real answer to this is that it depends on your application. You may want to publish from your camera, but you may not necessarily want to do this. For example, if your application is for watching a professor present a lecture, you would not want a student to publish. In that case you might implement some logic to determine if the person accessing the page was a professor or student and then decide from there. Otherwise you could also just create a button that waits for user input to publish.
For our scenario, though, we'll keep it simple and assume that you do want to publish immediately. In order to do this you need to call session.publish(). Starting the handler off with a log statement may also prove useful when debugging, so we'll add that too.
function sessionConnectedHandler(event) {
console.log("sessionConnectedHandler event executed.");
session.publish();
}
Once you publish, you will see a video of yourself and a stream will be created. This will cause a streamCreated event that will go out to everyone EXCEPT for yourself. You might think you don't need to implement a streamCreatedHandler since you never receive a streamCreated event when your stream goes out, but you need to remember that other people that use your page are being served the same page. This means that THEY will run the session.publish() method and you WILL receive a streamCreated event in those cases.
Again, while you will be able to subscribe to streams in this handler, don't feel like that is the only work flow. You could decide not to subscribe to a stream, or perhaps you want to implement some logic to send a message to others telling them that the user has subscribed and is now watching them. We'll go with the basic use case again and just subscribe right after our log statement. We do this by calling session.subscribe() and passing in the stream we want to subscribe to. We get the stream that created the event in the event variable passed in.
function streamCreatedHandler(event) {
console.log("streamCreatedHandler event executed.");
session.subscribe(event.stream);
}
Your end results should look like this:
That's it! You can now open two different browser tabs, enter your URL and see how someone would see your video chat. You might be wondering why your streams are mirrors of each other. This is because you see your own published stream as a mirror image. The stream you subscribe to from others, however, is not a mirror image, and since you are publishing and subscribing to yourself, you see both. If you have a web server that is accessible from another computer, you can see how this would look if two different people joined, which would be much more exciting.
Try opening another tab with the same URL. Before you do though, take a guess as to what will happen, and why.
You'll notice that the page always serves up one hard coded session. We've done that for this step to get
TROUBLESHOOTING
Because of all the moving parts in the environment setup, you may not be getting the results you expected for a number of reasons. Let's try to step through each possibility and narrow it down.
1. Is your web server up AND running?
2. Are you opening your web page through the web server?
3. Have you made a coding error?
The quickest way to test if you made a coding error or not is to try and paste our example in. If that doesn't work, you have something broken in your setup. If it does work, you can compare your code to ours line by line and narrow down where your error is coming from.
If you set up your web server in this step, you need to take two things into consideration. Either yo. Make sure your web server is running and that you are accessing the URL served by it. If you access the file directly from your filesystem, you will get an error.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment