Welcome folks today in this tutorial I will be talking about how to build a P2P (Peer to Peer) Video and text chat in Javascript Using Simple Peer and WebRTC
. All the source code of the tutorial are given as follows. A step by step youtube video is shown below.
Get Started
In order to get started with this application we need to install the module bundler
called as Browserify
which will bundle all of our code into a single javascript file called as bundle.js
.
npm i -g browserify
This will install browserify globally inside your system
Now go to your project directory and make a index.html file and copy paste the following code into it. First of all you need to install some dependencies for your project. Execute this command as follows
npm i simple-peer getusermedia
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <label>Your ID:</label><br/> <textarea id="yourId"></textarea><br/> <label>Other ID:</label><br/> <textarea id="otherId"></textarea> <button id="connect">connect</button><br/> <label>Enter Message:</label><br/> <textarea id="yourMessage"></textarea> <button id="send">send</button> <pre id="messages"></pre> <script src="bundle.js" charset="utf-8"></script> </body> </html> |
Now create your index.js
file which will hold the logic of your application. All the javascript code will be there
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
var getUserMedia = require('getusermedia') getUserMedia({ video: true, audio: false }, function (err, stream) { if (err) return console.error(err) var Peer = require('simple-peer') var peer = new Peer({ initiator: location.hash === '#init', trickle: false, stream: stream }) peer.on('signal', function (data) { console.log("signal") document.getElementById('yourId').value = JSON.stringify(data) }) document.getElementById('connect').addEventListener('click', function () { console.log("connect button clicked") var otherId = JSON.parse(document.getElementById('otherId').value) peer.signal(otherId) }) document.getElementById('send').addEventListener('click', function () { console.log("send button") var yourMessage = document.getElementById('yourMessage').value peer.send(yourMessage) }) peer.on('data', function (data) { console.log("data") document.getElementById('messages').textContent += data + '\n' }) peer.on('stream', function (stream) { console.log("stream") var video = document.createElement('video') document.body.appendChild(video) video.srcObject = stream video.play() }) }) |
Now make your bundle.js
file by executing this command as follows
browserify index.js -o bundle.js