Building P2P Video Chat Application using webRTC and Node.js

In this article, we will see how to build a peer to peer video chat application using webRTC and Node.js.Building P2P Video Chat Application using webRTC and Node.js

More Article on Node.js

Apache Kafka for Node.js developers

Implementing Redis Pub/Sub in Node.js

Complete Source code can be found here

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

Demo

Building P2P Video Chat Application using webRTC and Node.js

Screenshot 2019 09 01 at 1 43 48 PM

This article is referenced from this video

To Read More

Kubernetes for Nodejs developers

Do you keep hearing the word kubernetes in the tech community and you couldn't u...

TypeScript Interfaces vs Types

In this article, we will see what are interfaces and types and the difference be...

How to find project ideas to practi...

Ever wondered what how to get a real world experience on web development while w...

Building a Production-grade Nodejs,...

This article is the first part of building a production grade nodejs,graphql and...

Modern React Redux Tutorials with R...

This tutorial explain how you can build an application using modern react redux ...

Building a Piano with React Hooks

In this article, we will see how to build a piano with react hooks. Building a P...

TypeScript Basics - The Definitive ...

In this article, we will learn some basics of typescript which helps you to deve...

Here's why podman is more secured t...

In this article we will see about podman and why it is more secured way to run c...

What is gRPC ? How to implement gRP...

Everyone talks about gRPC. Have you ever wonder how it works or how to implement...