WEBRTC video conference using STUN TURN server with PEER.JS

bharathraj.eth
4 min readAug 26, 2020

--

create your own customize web conference app.

what is WEBRTC?

WebRTC is an open source project to enable realtime communication of audio, video and data in Web and native apps.

Api consist of predefined function and methods which will enable to stream the media contents.A WebRTC application will usually go through a common application flow. Accessing the media devices.It supports video, voice, and generic data to be sent between peers, allowing developers to build powerful voice- and video-communication solutions.

What is Signaling?

WebRTC uses RTCPeerConnection to communicate streaming data between browsers, but also needs a mechanism to coordinate communication and to send control messages, a process known as signaling.

if you work webrtc with Wifi and Mobile data WEBRTC must need STUN and TURN server

What is STUN and TURN server?

WebRTC is designed to work peer-to-peer, so users can connect by the most direct route possible. However, WebRTC is built to cope with real-world networking: client applications need to traverse NAT gateways and firewalls, and peer to peer networking needs fallbacks in case direct connection fails. As part of this process, the WebRTC APIs use STUN servers to get the IP address of your computer, and TURN servers to function as relay servers in case peer-to-peer communication fails.

will explain detail how to create STUN and TURN by next post

we will execute our webrtc project by using Node and Js library cool..!!

so lets jump in to the process.

step 1:

install npm dependency by running:

npm i express ejs socket.io uuidnpm i -g peer

why we using socket.io?

which will enable communicate based on event that is allow communicate back and forth with server easily. read more about socket.io

what is uuid ?

will enable to create dynamic url

what is peer.js

will enable to establish peer to peer connection between two servers. read more about peer.js

create Server.js in your route directory after configuring npm setup.

const express = require(‘express’)const app = express()const server = require(‘http’).Server(app)const io = require(‘socket.io’)(server)const { v4: uuidV4 } = require(‘uuid’)app.set(‘view engine’, ‘ejs’)app.use(express.static(‘public’))app.get(‘/’, (req, res) => {res.redirect(`/${uuidV4()}`)})app.get(‘/:room’, (req, res) => {res.render(‘room’, { roomId: req.params.room })})io.on(‘connection’, socket => {socket.on(‘join-room’, (roomId, userId) => {socket.join(roomId)socket.to(roomId).broadcast.emit(‘user-connected’, userId)socket.on(‘disconnect’, () => {socket.to(roomId).broadcast.emit(‘user-disconnected’, userId)})})})server.listen(3000)

you can mention any listen id by writing server listener.room id and user i d will be unique validate argument.

create public/script.js in route directory then add following code:

const socket = io(‘/’)const videoGrid = document.getElementById(‘video-grid’)const myPeer = new Peer({config: {‘iceServers’: [{ url: ‘stun:[your stun id]:[port]’ },{ url: ‘turn:[your turn id]:[port]’,username:’[turn username]’, credential: ‘[turn password]’ }]}});const myVideo = document.createElement(‘video’)myVideo.muted = trueconst peers = {}navigator.mediaDevices.getUserMedia({video: true,audio: true}).then(stream => {addVideoStream(myVideo, stream)myPeer.on(‘call’, call => {call.answer(stream)const video = document.createElement(‘video’)console.log(stream);call.on(‘stream’, userVideoStream => {addVideoStream(video, userVideoStream)})})socket.on(‘user-connected’, userId => {connectToNewUser(userId, stream)})})socket.on(‘user-disconnected’, userId => {if (peers[userId]) peers[userId].close()})myPeer.on(‘open’, id => {socket.emit(‘join-room’, ROOM_ID, id)})//console.log(myPeer);function connectToNewUser(userId, stream) {const call = myPeer.call(userId, stream)const video = document.createElement(‘video’)call.on(‘stream’, userVideoStream => {addVideoStream(video, userVideoStream)})call.on(‘close’, () => {video.remove()})peers[userId] = call}function addVideoStream(video, stream) {video.srcObject = streamvideo.addEventListener(‘loadedmetadata’, () => {video.play()})videoGrid.append(video)}

Note: port either you can use 3478 or 443.

next you can create view of your file under directory views/room.ejs

<!DOCTYPE html><html lang=”en”><head><meta charset=”UTF-8"><meta name=”viewport” content=”width=device-width, initial-scale=1.0"><meta http-equiv=”X-UA-Compatible” content=”ie=edge”><script>const ROOM_ID = “<%= roomId %>”</script><script defer src=”https://unpkg.com/peerjs@1.2.0/dist/peerjs.min.js"></script><script src=”/socket.io/socket.io.js” defer></script><script src=”script.js” defer></script><title>Document</title><style>#video-grid {display: grid;grid-template-columns: repeat(auto-fill, 300px);grid-auto-rows: 300px;}video {width: 100%;height: 100%;object-fit: cover;border-radius:5px;}</style></head><body><div id=”video-grid”></div></body></html>

cool..!!! your basic web conference/app is here you can improve the concept layout design everything by manipulating the code.

to run: npm server.js or npm start

Follow me on Twitter for more Technical and web3 threads:
https://twitter.com/rajdxb14

--

--

bharathraj.eth
bharathraj.eth

Written by bharathraj.eth

Dev | Solidity | Blockchain | Web3 | React | Laravel

Responses (2)