Sep 1, 2019· 6 mins to read

Building P2P Video Chat Application using webRTC and Node.js


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.

node p2p

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

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);
}

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

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);
  });

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

swarm.on("connect", function (peer, id) {
  peer.on("data", function (data) {
    //On receiving the data from peers, do some actions
  });
});

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

swarm.peers.forEach(function (peer) {
  peer.send("Data to Send");
});

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.

navigator.mediaDevices
  .getUserMedia({ video: true, audio: true })
  .then(function (stream) {
    //Gets Media Access
  });

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

const swarm = createSwarm(hub, {
  stream: stream,
});

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

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

Running the Application

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

$ npm run signalhub
$ npm run start

Demo

Building P2P Video Chat Application using webRTC and Node.js

demo

This article is referenced from this video

Copyright © Cloudnweb. All rights reserved.