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

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...