Building P2P Video Chat Application using webRTC and Node.js
Tags: showdev, webdev, tutorial, beginners
Published: 2019-09-01 10:26:25

---
title: Building P2P Video Chat Application using webRTC and Node.js
published: true
description: Building P2P Video Chat Application using webRTC and Node.js
tags: showdev,webdev,tutorial,beginners
canonical_url : https://cloudnweb.dev/2019/09/building-p2p-video-chat-application-using-webrtc-and-node-js/
---
<!-- wp:paragraph -->
<p>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</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>More Article on Node.js</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://cloudnweb.dev/2019/08/apache-kafka-for-node-js-developers/">Apache Kafka for Node.js developers</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://cloudnweb.dev/2019/08/implementing-redis-pub-sub-in-node-js-application/">Implementing Redis Pub/Sub in Node.js</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Complete Source code can be found <a href="https://github.com/ganeshmani/node-p2p">here</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is Peer to Peer Network?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":1310} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/09/nodep2p2.png" alt="" class="wp-image-1310"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>To learn more about <a href="https://www.youtube.com/watch?v=oCS05QSQ-1k">Peer-to-Peer Application</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Building Peer-to-Peer Application</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Firstly, there are few npm packages which helps to build the peer-to-peer applications in Node.js.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><a href="https://www.npmjs.com/package/signalhub">SignalHub</a></li><li><a href="https://github.com/mafintosh/webrtc-swarm">webRTC-swarm</a></li><li>simple-peer</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>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 <strong>SignalHub</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>SignalHub sends the messages to another to peer to connect.<strong> webRTC-swarm</strong> Connects through the SignalHub. Simple-peer makes the browser a peer node.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's build a video chat application using the webRTc Swarm,simple-peer.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create a file videoplayer.js and add the following code</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>module.exports = Player

function Player (data) {
  data = data || {}
  this.color = data.color || randomColor()
  this.x = data.x;
  this.y = data.y;
  this.top = data.top;
  this.left = data.left;
  this.name = data.name;
  this.element = document.createElement('video')
  Object.assign(this.element.style, {
    width: '40%',
    height: '50%',
    position: 'absolute',
    top: data.top+'px',
    left: data.left+'px',
    backgroundColor: this.color
  })
  document.body.appendChild(this.element)
}

Player.prototype.addStream = function (stream) {
  this.element.srcObject = stream
  this.element.play()
}

Player.prototype.update = function (data) {
  data = data || {}
  this.x = data.x || this.x
  this.y = data.y || this.y
  Object.assign(this.element.style, {
    top: this.y + 'px',
    left: this.x + 'px'
  })
}

function randomColor () {
  return '#' + Math.random().toString(16).substr(-6)
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>video player create a video element in the browser. we stream and manipulate the DOM element using webRTC communication.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create a file index.js and add the following code</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function (stream) {
    //This is used for Signaling the Peer    
    const signalhub = require('signalhub')
    const createSwarm = require('webrtc-swarm')
    //Creates the Signal rub running in the mentioned port
    const hub = signalhub('my-game', [
      'http://localhost:8080'
    ])
    const swarm = createSwarm(hub, {
      stream: stream
    })
    //Creates a video player
    const Player = require('./videoplayer.js')
    const you = new Player({ x: 0, y : 0 ,color : 'black',left : 0,top : 0})
    you.addStream(stream)
  
    const players = {}
    swarm.on('connect', function (peer, id) {
      if (!players[id]) {
        players[id] = new Player({
            x : 300,
            y : 0,
            left : 200,
            top : 0,
            color : 'red'
        })
        peer.on('data', function (data) {
          data = JSON.parse(data.toString())
          players[id].update(data)
        })
        players[id].addStream(peer.stream)
      }
    })
    //On webRTC Disconnets
    swarm.on('disconnect', function (peer, id) {
      if (players[id]) {
        players[id].element.parentNode.removeChild(players[id].element)
        delete players[id]
      }
    })

  
    setInterval(function () {
        console.log("Interval Call");
      you.update()
      
      const youString = JSON.stringify(you)
      swarm.peers.forEach(function (peer) {
        peer.send(youString)
      })
    }, 100)
  })</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Firstly, we create a webRTC swarm and maps it with the SignalHub.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>swarm.on('connect',function(peer,id){
     peer.on('data',function(data){
         //On receiving the data from peers, do some actions
    });
});</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>After that, swarm listener listens for a connection. when other peers connects, we start to listen for the peer to send the data.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code> swarm.peers.forEach(function (peer) {
        peer.send("Data to Send")
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In webRTC swarm, we find our peer node and send the data to all other nodes.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Video Stream in Peer-to-Peer</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Mainly, to stream a video. we need to get media to access from the web API. you can enable this using the following code.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function (stream) {
    //Gets Media Access
});</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>After that, you need to add the stream to the webRTC swarm to access the data in the peer network.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code> const swarm = createSwarm(hub, {
      stream: stream
    })</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Finally, you need to add the stream to the video element.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>Player.prototype.addStream = function (stream) {
  this.element.srcObject = stream
  this.element.play()
}</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>Running the Application</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To run the application, you need to run the SignalHub first and run the server.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>$ npm run signalhub
$ npm run start</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>Demo</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>

Building P2P Video Chat Application using webRTC and Node.js

</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":1314} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/09/Screenshot-2019-09-01-at-1.43.48-PM-1024x566.png" alt="" class="wp-image-1314"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>This article is referenced from <a href="https://www.youtube.com/watch?v=IqPJb6o_S1Q">this</a> video</p>
<!-- /wp:paragraph -->