Build a WebRTC signaling chat app with JavaScript
A basic understanding of JavaScript is needed to follow this tutorial.
Pusher is perfect for instantaneously distributing messages amongst people and devices. This is exactly why Pusher is a great choice for signalling in WebRTC, the act of introducing two devices in realtime so they can make their own peer-to-peer connection.
Getting started
Making your own peer-to-peer chat application using WebRTC is incredibly simple thanks to DataChannel.js and the Pusher API.
Let’s take a look at how to get everything up and running.
To complete your peer-to-peer chat app you’ll need some credentials from Pusher. It’s worth creating a free account now so you have them prepared for later on in the guide. It only takes a minute to do and it’ll save you time later on.
Preparation
The first thing you’ll do is to get the HTML document set up, referencing the stylesheets and scripts that you require. These are:
- Bootstrap for general layout and styling
- Zepto for JavaScript nicities and AJAX requests (or jQuery)
- Pusher for singalling via realtime WebSockets
- DataChannel.js for WebRTC abstraction
We won’t worry about the styling in this guide so feel free to check out the defaults or make your own.
<!-- public/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Pusher WebRTC DataChannel Demo</title>
<!-- Bootstrap for general layout and styling -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Our WebRTC application styling -->
<link rel="stylesheet" type="text/css" href="style/datachannel-demo.css">
</head>
<body>
<!-- Zepto for AJAX -->
<script src="//cdnjs.cloudflare.com/ajax/libs/zepto/1.1.3/zepto.min.js"></script>
<!-- Pusher for WebRTC signalling -->
<script src="//js.pusher.com/2.2/pusher.js"></script>
<!-- DataChannel.js for WebRTC functionality -->
<script src="//webrtc-experiment.com/DataChannel.js"></script>
<!-- Our WebRTC application -->
<script src="js/datachannel-demo.js"></script>
</body>
</html>
This won’t look like much yet, though you’ll get to that later. For now, let’s move on to setting up WebRTC.
Pusher and DataChannel.js setup
Now you’ve got the basic HTML document prepared you can look at setting up the fundamentals for DataChannel.js and Pusher.
The first thing you need to do is to initialise DataChannel.js and store a reference to it in a variable. From there you can set a unique ID for the local user as per the one generated by DataChannel.js in window.userid
.
// public/js/datachannel-demo.js
// Initialise DataChannel.js
var datachannel = new DataChannel();
// Set the userid based on what has been defined by DataChannel
// https://github.com/muaz-khan/WebRTC-Experiment/tree/master/DataChannel#use-custom-user-ids
datachannel.userid = window.userid;
That’s nearly all you need for setting up DataChannel.js, though you’ll add a couple more things later on. For now, it’s time to set up Pusher. If you haven’t already, create a free account and get your application credentials ready as you’ll be needing them.
All you need to do here is initialise a new connection to Pusher using your application key and monitoring the connection state to store a reference to the WebSocket connection ID for the local user.
If you want to debug what Pusher is doing then you can uncomment the Pusher.log
function and everything will be displayed in your browser console. Otherwise, there are a variety of ways to further debug things.
// public/js/datachannel-demo.js
// Open a connection to Pusher
var pusher = new Pusher("PUSHER_APP_KEY");
// Storage of Pusher connection socket ID
var socketId;
// Pusher.log = function(message) {
// if (window.console && window.console.log) {
// window.console.log(message);
// }
// };
// Monitor Pusher connection state
pusher.connection.bind("state_change", function(states) {
switch (states.current) {
case "connected":
socketId = pusher.connection.socket_id;
break;
case "disconnected":
case "failed":
case "unavailable":
break;
}
});
At this point you have a connection to Pusher but it doesn’t know about DataChannel.js or what to do with it. Let’s change that.
WebRTC signaller - client
A peer-to-peer WebRTC connection cannot happen without devices knowing who to connect to - this is known as signalling. For devices to know about each other their details need to be shared via a separate system, which is where Pusher comes in.
By using Pusher you’re able to share details between devices easily and in realtime, all without having to get your hands dirty with low-level WebRTC APIs or complex communication mechanisms. Using Pusher also means you don’t have to write your own signalling server, in fact you barely have to do anything on your server at all. Nifty!
Creating a new signaller for DataChannel.js can be achieved by overwriting the openSignalingChannel method with one of your own. In this case, you’re going to write a Pusher-specific one.
// Set custom Pusher signalling channel
// https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Signaling.md
datachannel.openSignalingChannel = function(config) {
var channel = config.channel || this.channel || "default-channel";
var xhrErrorCount = 0;
var socket = {
send: function(message) {
$.ajax({
type: "POST",
url: "/message",
data: {
socketId: socketId,
channel: channel,
message: message
},
timeout: 1000,
success: function(data) {
xhrErrorCount = 0;
},
error: function(xhr, type) {
// Increase XHR error count
xhrErrorCount++;
// Stop sending signaller messages if it's down
if (xhrErrorCount > 5) {
console.log("Disabling signaller due to connection failure");
datachannel.transmitRoomOnce = true;
}
}
});
},
channel: channel
};
// Subscribe to Pusher signalling channel
var pusherChannel = pusher.subscribe(channel);
// Call callback on successful connection to Pusher signalling channel
pusherChannel.bind("pusher:subscription_succeeded", function() {
if (config.callback) config.callback(socket);
});
// Proxy Pusher signaller messages to DataChannel
pusherChannel.bind("message", function(message) {
config.onmessage(message);
});
return socket;
};
The first 2 things you do in openSignalingChannel
is to store a reference to the channel name that you want to monitor for other devices, as well as creating a variable to count any connection errors.
The most important part of the signaller is the socket
object which contains the send
method and channel
reference. This is the core part of the signaller and is used to send messages from the local user.
In this case, you’re using an AJAX POST request to the /message
endpoint on your server. The AJAX request contains the socketId
from Pusher that you stored earlier, as well as the channel
and message
to be sent to that channel. Passing the socketId
means that you can make sure the local user isn’t sent their own messages. You’ll create the /message
endpoint later on.
Everything else in the AJAX request is handling errors, effectively preventing the signaller from continuously trying and failing to send messages when there’s no Internet connection.
After the socket
object you set up the Pusher-specific bits and pieces, like subscribing to the signalling channel and setting up en event listener for a successful subscription. At which point you call the callback
to notify DataChannel.js that everything is ready.
The last Pusher-related bit is to set up a listener for incoming signalling messages from other devices. This is achieved by using Pusher’s bind
method and attaching it to the message
event. Within the event handler you pass through the messages to the DataChannel.js onmessage
method.
WebRTC signaller - server
To complete the signalling process you need to set up a small server-side handler for the /message
endpoint. All this does is take received messages and proxy them to other devices through Pusher’s realtime WebSocket network.
You can do this on any server-side platform that Pusher supports, though Node.js is being used here as an example.
// server.js
var express = require("express");
var bodyParser = require("body-parser");
var errorHandler = require("errorhandler");
var app = express();
var root = __dirname + "/public";
// -------------------------------------------------------------
// SET UP PUSHER
// -------------------------------------------------------------
var Pusher = require("pusher");
var pusher = new Pusher({
appId: "PUSHER_APP_ID",
key: "PUSHER_APP_KEY",
secret: "PUSHER_APP_SECRET"
});
// -------------------------------------------------------------
// SET UP EXPRESS
// -------------------------------------------------------------
// Parse application/json and application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Simple logger
app.use(function(req, res, next){
console.log("%s %s", req.method, req.url);
console.log(req.body);
next();
});
// Error handler
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
// Serve static files from directory
app.use(express.static(root));
// Message proxy
app.post("/message", function(req, res) {
var socketId = req.body.socketId;
var channel = req.body.channel;
var message = req.body.message;
pusher.trigger(channel, "message", message, socketId);
res.send(200);
});
// Open server on specified port
console.log("Starting Express server");
app.listen(process.env.PORT || 5001);`</pre>
Of all the code, the app.post("/message", function(req, res) {...});
part is the only bit you need to worry about. This is the message proxy from your AJAX requests to Pusher’s realtime API. The socketId
is used here to make sure the message isn’t sent to the user who sent the AJAX request.
This is all you need to do on the server-side so let’s take a moment to see if everything is working ok.
Manually testing WebRTC
Now you’ve got the main WebRTC functionality connected up it’s time to test that you can actually make a connection using it. The first thing to do is spin up whatever server you’re using and load up your WebRTC page in a browser.
If you’re using the Node.js example then you’d run something like the following in your terminal of choice:
$ cd /path/to/your/app
$ node server.js
From here you’ll want to load the app in your browser and then open the developer console:
- Chrome — View -> Developer -> JavaScript Console
- Firefox — Tools -> Web Developer -> Web Console
The datachannel
object in your app is available globally so you can access it from the developer console. Let’s prepare a WebRTC connection using the datachannel.open()
method:
This will prepare a WebRTC connection and monitor the Pusher signalling server for other devices that connect. You’ll not see any output yet but the next step will show us if everything worked or not.
Without closing the current page, load up the app in a new tab and open the developer console for it. This time you want to use the datachannel.connect()
method to look for other devices wanting to open a WebRTC connection:
This will prepare a WebRTC connection and look for open channels via the signalling server. Seeing as you opened one previously, you should now begin to see a flood of messages in the developer console:
These messages, shared via the signalling server, contain all the necessary details for making a peer-to-peer connection between 2 devices. It’s not important to fully understand them but you can read more about them should you wish.
At this point you have a fully functional peer-to-peer connection between your browser tabs using WebRTC! If you don’t, then you’ll want to check your Pusher Debug Console to see if the messages went through:
If they didn’t, it’s time to uncomment the Pusher.log
method and dig into the problem.
Adding chat HTML
Now that you know the WebRTC connection works it’s time to put together the chat interface:
<!-- public/index.html -->
<!-- Chat demo -->
<div class="demo">
<div class="demo-connect">
<input type="text" class="demo-chat-channel-input form-control" placeholder="Channel name"></input>
<button class="demo-chat-create btn btn-primary">Create</button>
<button class="demo-chat-join btn btn-warning">Join</button>
</div>
<div class="demo-chat inactive">
<div class="demo-chat-input">
<input name="message" class="demo-chat-message-input form-control" placeholder="Message"></input>
<button class="demo-chat-send btn btn-primary">Send</button>
</div>
<ul class="demo-chat-messages list-group">
<li class="list-group-item" data-remove="true">No chat messages available</li>
</ul>
</div>
<footer>
<a href="http://pusher.com">Pusher</a> powered peer-to-peer chat
</footer>
</div>
<!-- / Chat demo -->
It should be relatively straight forward if you know much about HTML. The main thing to point out is that you’re splitting the chat app into 2 panels; demo-connect
for connecting to a chat, and demo-chat
for the actual chat interface. The demo-chat
panel is hidden with CSS until you’re ready to show it after a successful WebRTC connection.
Connection logic
The chat interface is pretty useless right now, it doesn’t actually do anything if you click the buttons. The only way to make a connection is to manually trigger it via the developer console. Let’s change that:
// public/js/datachannel-demo.js
var onCreateChannel = function() {
var channelName = cleanChannelName(channelInput.value);
if (!channelName) {
console.log("No channel name given");
return;
}
disableConnectInput();
datachannel.open(channelName);
};
var onJoinChannel = function() {
var channelName = cleanChannelName(channelInput.value);
if (!channelName) {
console.log("No channel name given");
return;
}
disableConnectInput();
// Search for existing data channels
datachannel.connect(channelName);
};
var cleanChannelName = function(channel) {
return channel.replace(/(\W)+/g, "-").toLowerCase();
};
var disableConnectInput = function() {
channelInput.disabled = true;
createChannelBtn.disabled = true;
joinChannelBtn.disabled = true;
};
// Demo DOM elements
var channelInput = document.querySelector(".demo-chat-channel-input");
var createChannelBtn = document.querySelector(".demo-chat-create");
var joinChannelBtn = document.querySelector(".demo-chat-join");
// Set up DOM listeners
createChannelBtn.addEventListener("click", onCreateChannel);
joinChannelBtn.addEventListener("click", onJoinChannel);`</pre>
It looks like a lot but really there are 2 main things happening here; you can create a new chat room by typing a name and clicking create (eg. demochannel.open()
), or you can connect to an existing channel by typing the name and clicking join (eg. demochannel.connect()
).
Aside from the core event listeners for the buttons, the rest is mainly logic to clean up channel names and disable input while creating a WebRTC connection.
Messaging logic
As with the connect buttons the chat interface itself currently doesn’t do anything special, which is pretty useless. The following code will turn the interface into something that reacts when you type messages and will display incoming messages from others:
// public/js/datachannel-demo.js
var onSendMessage = function() {
var message = messageInput.value;
if (!message) {
console.log("No message given");
return;
}
datachannel.send(message);
addMessage(message, window.userid, true);
messageInput.value = "";
};
var onMessageKeyDown = function(event) {
if (event.keyCode == 13){
onSendMessage();
}
};
var addMessage = function(message, userId, self) {
var messages = messageList.getElementsByClassName("list-group-item");
// Check for any messages that need to be removed
var messageCount = messages.length;
for (var i = 0; i < messageCount; i++) {
var msg = messages[i];
if (msg.dataset.remove === "true") {
messageList.removeChild(msg);
}
};
var newMessage = document.createElement("li");
newMessage.classList.add("list-group-item");
if (self) {
newMessage.classList.add("self");
newMessage.innerHTML = "<span class='badge'>You</span><p>" + message + "</p>";
} else {
newMessage.innerHTML = "<span class='badge'>" + userId + "</span><p>" + message + "</p>"
}
messageList.appendChild(newMessage);
};
var messageInput = document.querySelector(".demo-chat-message-input");
var sendBtn = document.querySelector(".demo-chat-send");
var messageList = document.querySelector(".demo-chat-messages");
sendBtn.addEventListener("click", onSendMessage);
messageInput.addEventListener("keydown", onMessageKeyDown);
Like what you did with the connect buttons, the majority of code here is setting up event listeners for the chat input and send button. The onSendMessage
method handles the sending of your messages after clicking the send button, and the addMessage
method handles adding received messages to the message interface. The only other thing is the onMessageKeyDown
method which is used to check for the return key being pressed when typing a message and using that to send it without having to click the send button.
Tying everything together
Although pretty much everything is done now, the chat interface won’t actually display yet. To do this you need to hook up the DataChannel.js events for successfully connecting via WebRTC, and for receiving messages over WebRTC:
// public/js/datachannel-demo.js
// Set up DataChannel handlers
datachannel.onopen = function (userId) {
document.querySelector(".demo-connect").classList.add("inactive");
document.querySelector(".demo-chat").classList.remove("inactive");
messageInput.focus();
};
datachannel.onmessage = function (message, userId) {
addMessage(message, userId);
};
This should already make sense to you, though all that’s really happening is that you hide the connect panel and show the chat panel when a WebRTC connection is detected (datachannel.onopen
), and you call addMessage
on the chat interface when a new message is received (datachannel.onmessage
).
Wrapping up
In this tutorial you learnt how to put together your own WebRTC chat application using Pusher as a signalling server. We covered setting up a WebRTC connection using DataChannel.js and connecting that up to a chat UI using simple JavaScript.
From here you can take things further and explore more complex chat applications by adding in better message security, private messages, multi-user chat rooms, and more!
27 July 2016
by Pusher team