Node.js Video Chat Tutorial

Video ChatThe video chat revolution is bringing application interactivity to new frontiers.  Whether used to provide real-time communication, improve customer service, or give technical training, the prevalence of high-quality video cameras on smart phones and high-speed Internet access makes video chat applications easy to both build and deploy.

Prior to the development of WebRTC, cross-platform video app development was a challenge.  Each browser, PC, and device often had unique nuances in implementation.  Google set out to solve that in 2011 by releasing the source code for a browser-based real-time communication tool and organized the WebRTC protocol under the W3C.

WebRTC is currently supported by Chrome and Firefox, and has plug-in based support for Internet Explorer and Safari.  The API enables using HTML5 and JavaScript to send and receive video feeds.  JavaScript developers can create systems that layer interactive elements on top of the video feeds and send additional data such as file, voice, and screen captures.

One of the easiest ways to get started with WebRTC is by using a video chat platform such as OpenTok.  OpenTok extends WebRTC by providing plugins for cross-browser compatibility with Internet Explorer and Safari, and takes care of routing fallback in case Peer-to-Peer connections fail.  In addition, OpenTok provides the capability to archive video chats if necessary for an application.

Although alternatives exist to OpenTok, each has its unique benefits and drawbacks.  Wowza, the platform OpenTok uses for its video chat, has cheaper pricing for large streaming sessions with one host and many subscribers, such as a concert performance or a webinar.  P2P WebRTC technology such as PeerJS is free and the best choice for direct P2P connections, however these might fail if the firewall cannot be traversed.  OpenTok is an excellent choice for commercial applications that require one-to-one video chat that will work across many browsers and network configurations.

Creating an OpenTok video chat application requires two components: the web service that will manage the sessions, and the client app that will connect to the server and stream the video.  The OpenTok REST API is compatible with Node.js, and the Node.js platform is ideally suited for this type of application.

The sample code below creates a Node.js router endpoint at http://server/chat.  When requested, the server will connect to OpenTok using the API Key and API Secret, and create a new Session and Token that will be passed to the client.  It’s important to never provide the API Secret to the end-user so that they will not have full access to your OpenTok account.  The server code below can be pasted into a standard Express installation to replace the “routes\index.js” router.

var express = require('express');
var router = express.Router();
var OpenTok = require('opentok');

var opentok_API_KEY = 'API_KEY';
var opentok_API_SECRET = 'API_SECRET';
var sessionId = '';
var opentok;

function gen_token(res){
var token = opentok.generateToken(sessionId);
res.end(JSON.stringify({
'api_key':opentok_API_KEY,

'sessionID':sessionId,
'token':token
}));
}

router.get('/chat', function(req, res) {
if(!opentok) opentok = new OpenTok(opentok_API_KEY, opentok_API_SECRET);
if(!sessionId){
opentok.createSession({mediaMode:"routed", archiveMode:'always'}, function(error, result) {
if (error) { console.log("Error creating session:", error) }
else {
sessionId = result.sessionId;
console.log("Session ID: " + sessionId);
gen_token(res);
}
});
}
else gen_token(res);
});

module.exports = router;

Before running the server, be sure to install the opentok NPM library.  In addition, the API_KEY and API_SECRET need to be replaced in the code with your account credentials from OpenTok.  The chat route creates a new session with OpenTok, and then passes the results back to the client using the gen_token function.

Next, create the HTML / JavaScript client that will connect to the server, request a Session ID and Token, and set up the Video Chat.  Create a file “public\chat.htm” in a standard Express installation, and paste the following code.

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
<style type="text/css">body { height:100%; width:100%; margin:0; padding:0; font-family:Arial; }</style>
<script src='//static.opentok.com/v2/js/opentok.min.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var lastclick = 0,OT_session,publisher,subscriber,stream;
$(document).ready(function(){ connect(); });
function connect(){
$.ajax({
url: '/chat',
dataType: 'json',
cache: false,
complete: function(rslt){ start_ot(rslt.responseJSON); }
});
}
function start_ot(config){
var errhandler = function(error) { if (error) { console.log(error); } };
if (OT.checkSystemRequirements() == 1) {
OT_session = OT.initSession(config.api_key, config.sessionID);
OT_session.connect(config.token, function(error) {
if (error) { console.log("Error connecting: ", error.code, error.message); }
else {
OT_session.on('streamCreated', function(event) {
stream = event.stream;
var subscriberProperties = {insertMode: 'append', audioVolume: 100, width:'100%', height:'100%'};
subscriber = OT_session.subscribe(stream, 'sub_viewer', subscriberProperties, errhandler);
});
var publisherProperties = {insertMode: "append", width:'100%', height:'100%', name: "John Smith"};
publisher = OT.initPublisher('pub_viewer', publisherProperties, errhandler);
OT_session.publish(publisher, errhandler);
}
});
}
}
</script>
<table style="width:100%;height:100%;"><tr>
<td width="50%">
<div id="sub_viewer" style="background-color:black;width:100%;height:100%;display:inline-block;"></div>
</td>
<td width="50%">
<div id="pub_viewer" style="background-color:black;width:100%;height:100%;display:inline-block;"></div>
</td>
</tr></table>
</body>
</html>

The client code initially calls the server “/chat” service in the connect function, and receives back the OpenTok Session ID and Token.  Upon receipt, it then calls the start_ot function that uses the OpenTok JS library to initialize the session, and display both the local webcam and remote partner webcam in HTML elements on the page.

In order to test the app, find two Android devices or desktop PCs with the Chrome browser, and navigate to http://server/chat.htm, replacing the server with your local hostname and port.  On most standard Express installations, this will be http://hostname:3000/chat.htm.

This tutorial only begins to touch on the capabilities that video chat can bring to modern applications.  Whether integrating with 3D to create augmented reality applications, implementing image recognition capabilities, or creating interactive games, developers are only beginning to explore the bright future that video will bring to the next generation of applications.

Written by Andrew Palczewski

About the Author
Andrew Palczewski is CEO of apHarmony, a Chicago software development company. He holds a Master's degree in Computer Engineering from the University of Illinois at Urbana-Champaign and has over ten years' experience in managing development of software projects.
Google+

RSS Twitter LinkedIn Facebook Email

2 thoughts on “Node.js Video Chat Tutorial”

  1. WebRTC is a collection of communications protocols and APIs that enable real-time peer to peer connections within the browser. It’s perfect for multiplayer games, chat, video and voice conferences or filesharing. WebRTC is available in most modern browsers expect Safari. It’s currently supported by Chrome, Firefox, Edge and Opera. Safari has listed support for WebRTC as being in development.

Leave a Reply to Emma Thomsen Cancel reply

Your email address will not be published. Required fields are marked *