In today’s topic, we are driving into WebRTC (Web Real-Time Communication), a powerful technology that enables real-time audio, video, and data communication directly between web browsers and mobile applications. In this blog post, we will explore the implementation of WebRTC using Node.js and React, highlighting its prerequisites, the implementation process, advantages, and concluding thoughts.
Before delving into the implementation of WebRTC, it’s essential to ensure that you have the following prerequisites in place:
Step 1: Set Up the Node.js Server
Create a new directory for your project and set up a Node.js server.
mkdir webrtc-video-stream cd webrtc-video-stream npm init -y npm install express socket.io cors
Create a server file, e.g. server.js, with the following content:
const express = require('express'); const http = require('http'); const { Server } = require('socket.io'); const app = express(); const server = http.createServer(app); const io = new Server(server,{ cors: { origin: "*", credentials: true } }); const cors = require('cors'); app.use(cors({ origin: '*', // Replace with your React app's domain methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', credentials: true, // Allow cookies to be sent with the request if needed })); io.on("connection", function (socket) { console.log("connected"); socket.on("join", function (data) { socket.join(data.roomId); socket.room = data.roomId; const sockets = io.sockets.adapter.rooms.get(data.roomId); if (sockets.size === 1) { return socket.emit("init"); } else { if (sockets.size === 2) { io.to(data.roomId).emit("ready"); } else { socket.room = null; socket.leave(data.roomId); socket.emit("full"); } } }); socket.on("signal", (data) => { io.to(data.room).emit("desc", data.desc); }); socket.on("disconnect", () => { const roomId = Object.keys(socket.adapter.rooms)[0]; if (socket.room) { io.to(socket.room).emit("disconnected"); } }); }); server.listen(5000, () => { console.log('Server is running on http://localhost:5000'); });
In the above code,
This line of code establishes a connection between the server and the client. It listens for a “connection” event and executes the callback function when a client connects to the server.
This code block listens for a “join” event emitted by the client. When a client emits a “join” event, the server executes the callback function and performs the following actions:
This code block listens for a “signal” event emitted by the client. When a client emits a “signal” event, the server executes the callback function and emits a “desc” event to all sockets in the same room as the client. The data passed in the “signal” event is also included in the “desc” event.
This code block listens for a “disconnect” event emitted by the client. When a client disconnects from the server, the server executes the callback function and performs the following actions:
The server retrieves the roomId of the first room in which the socket is present. If the socket is associated with a room (socket.room is not null), the server emits a “disconnected” event to all sockets in the same room using io.to(socket.room).emit(“disconnected”).
Create a new directory for your React client and initialize a React app.
cd .. npx create-react-app client cd client npm install simple-peer socket.io-client
Replace the contents of src/App.js with the following:
import React, { useEffect, useRef, useState } from "react"; import io from "socket.io-client"; import SimplePeer from "simple-peer"; const App = () => { const socket = io("http://localhost:5000"); const localVideoRef = useRef(); const remoteVideoRef = useRef(); const peerRef = useRef(); useEffect(() => { navigator.mediaDevices .getUserMedia({ video: true, audio: true }) .then((stream) => { localVideoRef.current.srcObject = stream; socket.on("offer", (offer) => { peerRef.current = new SimplePeer({ initiator: false, trickle: false, stream, }); peerRef.current.signal(offer); peerRef.current.on("signal", (data) => { socket.emit("answer", { target: offer.target, answer: data }); }); peerRef.current.on("stream", (remoteStream) => { remoteVideoRef.current.srcObject = remoteStream; }); peerRef.current.on("data", (data) => { // Handle data communication between peers if needed }); }); socket.emit("join-call"); // Signal that you want to join a call }) .catch((error) => { console.error("Error accessing webcam:", error); }); // Clean up the socket connection and media streams on unmount return () => { if (peerRef.current) { peerRef.current.destroy(); } socket.disconnect(); }; }, []); return ( <div> <div> <video ref={localVideoRef} autoPlay playsInline muted /> </div> <div> <video ref={remoteVideoRef} autoPlay playsInline /> </div> </div> ); }; export default App;
In the above code,
The useEffect hook is used to perform side effects in functional components. It takes a callback function as its first argument and an optional array of dependencies as its second argument. In this code, useEffect is used to initialize the video call and clean up the resources when the component is unmounted.
This function is used to access the user’s webcam and microphone. It returns a promise that resolves to a MediaStream object containing the user’s audio and video streams.
The socket object is used to establish a connection with the server and exchange signalling messages with other participants in the video call. It emits and listens to events such as ‘offer’ and ‘answer’ to negotiate the connection between peers.
The SimplePeer library is used to create a WebRTC peer connection between the local user and the remote user. It handles the signalling process and establishes a direct media stream connection between the peers.
You can refer to my GitHub for the detailed guide!
In conclusion, WebRTC stands as a formidable technology that unlocks the potential for real-time communication within web applications. By embarking on the journey of implementing WebRTC with the dynamic duo of Node.js and React, you have the opportunity to craft interactive, engaging, and innovative applications with ease.
With its real-time prowess, peer-to-peer architecture, cross-platform adaptability, and robust security measures, WebRTC emerges as an invaluable addition to your development toolkit. Harness its capabilities, explore its potential, and embark on a journey of creating applications that leverage the transformative power of real-time communication.
How to Effectively Hire and Manage a Remote Team of Developers
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project. Â
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.Â
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork