Skip to main content

Building P2P Video Chat Application using webRTC and Node.js

What is Peer to Peer Network?

Peer to Peer Network is a network where the client acts as a server. there will be no centralized server in peer to peer network.

nodep2p2

To learn more about Peer-to-Peer Application

Building Peer-to-Peer Application

Since we don't need a server in a peer-to-peer application, you may think what would be the role of Node.js here. we build a peer-to-peer application in node.js an run that in a browser.

Firstly, there are few npm packages which helps to build the peer-to-peer applications in Node.js.

Mainly, To connect the peer with another peer. we need to tell other peers to connect with our peer. To solve this problem, we are using SignalHub.

SignalHub sends the messages to another to peer to connect. webRTC-swarm Connects through the SignalHub. Simple-peer makes the browser a peer node.

Let's build a video chat application using the webRTc Swarm,simple-peer.

create a file videoplayer.js and add the following code

1module.exports = Player
2
3function Player(data) {
4 data = data || {}
5 this.color = data.color || randomColor()
6 this.x = data.x
7 this.y = data.y
8 this.top = data.top
9 this.left = data.left
10 this.name = data.name
11 this.element = document.createElement("video")
12 Object.assign(this.element.style, {
13 width: "40%",
14 height: "50%",
15 position: "absolute",
16 top: data.top + "px",
17 left: data.left + "px",
18 backgroundColor: this.color,
19 })
20 document.body.appendChild(this.element)
21}
22
23Player.prototype.addStream = function(stream) {
24 this.element.srcObject = stream
25 this.element.play()
26}
27
28Player.prototype.update = function(data) {
29 data = data || {}
30 this.x = data.x || this.x
31 this.y = data.y || this.y
32 Object.assign(this.element.style, {
33 top: this.y + "px",
34 left: this.x + "px",
35 })
36}
37
38function randomColor() {
39 return (
40 "#" +
41 Math.random()
42 .toString(16)
43 .substr(-6)
44 )
45}

video player create a video element in the browser. we stream and manipulate the DOM element using webRTC communication.

create a file index.js and add the following code

1navigator.mediaDevices
2 .getUserMedia({ video: true, audio: true })
3 .then(function(stream) {
4 //This is used for Signaling the Peer
5 const signalhub = require("signalhub")
6 const createSwarm = require("webrtc-swarm")
7 //Creates the Signal rub running in the mentioned port
8 const hub = signalhub("my-game", ["http://localhost:8080"])
9 const swarm = createSwarm(hub, {
10 stream: stream,
11 })
12 //Creates a video player
13 const Player = require("./videoplayer.js")
14 const you = new Player({ x: 0, y: 0, color: "black", left: 0, top: 0 })
15 you.addStream(stream)
16
17 const players = {}
18 swarm.on("connect", function(peer, id) {
19 if (!players[id]) {
20 players[id] = new Player({
21 x: 300,
22 y: 0,
23 left: 200,
24 top: 0,
25 color: "red",
26 })
27 peer.on("data", function(data) {
28 data = JSON.parse(data.toString())
29 players[id].update(data)
30 })
31 players[id].addStream(peer.stream)
32 }
33 })
34 //On webRTC Disconnets
35 swarm.on("disconnect", function(peer, id) {
36 if (players[id]) {
37 players[id].element.parentNode.removeChild(players[id].element)
38 delete players[id]
39 }
40 })
41
42 setInterval(function() {
43 console.log("Interval Call")
44 you.update()
45
46 const youString = JSON.stringify(you)
47 swarm.peers.forEach(function(peer) {
48 peer.send(youString)
49 })
50 }, 100)
51 })

Firstly, we create a webRTC swarm and maps it with the SignalHub.

1swarm.on("connect", function(peer, id) {
2 peer.on("data", function(data) {
3 //On receiving the data from peers, do some actions
4 })
5})

After that, swarm listener listens for a connection. when other peers connects, we start to listen for the peer to send the data.

1swarm.peers.forEach(function(peer) {
2 peer.send("Data to Send")
3})

In webRTC swarm, we find our peer node and send the data to all other nodes.

Video Stream in Peer-to-Peer

Mainly, to stream a video. we need to get media to access from the web API. you can enable this using the following code.

1navigator.mediaDevices
2 .getUserMedia({ video: true, audio: true })
3 .then(function(stream) {
4 //Gets Media Access
5 })

After that, you need to add the stream to the webRTC swarm to access the data in the peer network.

1const swarm = createSwarm(hub, {
2 stream: stream,
3})

Finally, you need to add the stream to the video element.

1Player.prototype.addStream = function(stream) {
2 this.element.srcObject = stream
3 this.element.play()
4}

Running the Application

To run the application, you need to run the SignalHub first and run the server.

1$ npm run signalhub
2$ npm run start

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...