Audio and Video Peer-to-Peer Calling with Node.js, Peer.js, and Socket.io

Posted by

Node.js + Peer.js + Socket.io: Audio/Video Peer-to-Peer Calling

Node.js + Peer.js + Socket.io: Audio/Video Peer-to-Peer Calling

Node.js, Peer.js, and Socket.io are three powerful technologies that, when combined, enable peer-to-peer audio and video calling in web applications. This article will explore how to use these technologies to create a simple peer-to-peer calling system.

Setting up Node.js server

First, we need to set up a Node.js server to handle the signaling and data exchange between peers. We can use the express package to create a simple HTTP server:


const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  // Handle signaling and data exchange between peers
});

http.listen(3000, () => {
  console.log('Server is running on port 3000');
});
  

Integrating Peer.js

Next, we can integrate the peer.js library to handle the peer connection management. We can include the Peer.js script in our HTML file:


<script src="https://cdn.jsdelivr.net/npm/peerjs@1.3.1/dist/peerjs.min.js"></script>
  

Creating the front-end interface

We can create a simple front-end interface for initiating and receiving peer-to-peer calls. We can use the getUserMedia API to access the user’s microphone and camera:


navigator.mediaDevices.getUserMedia({ audio: true, video: true })
  .then((stream) => {
    // Display the local video stream
  })
  .catch((error) => {
    console.error('Error accessing media devices:', error);
  });
  

Handling the signaling and data exchange

We can use the socket.io library to handle the signaling and data exchange between peers. When a peer wants to initiate a call, they can send a signal to the server, which will then relay the signal to the recipient peer. Once the signaling is complete, the peers can establish a direct peer-to-peer connection for audio and video streaming.

Conclusion

Node.js, Peer.js, and Socket.io provide a powerful foundation for building peer-to-peer audio and video calling in web applications. By integrating these technologies, developers can create seamless and efficient real-time communication experiences for users.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@pasdes6091
11 months ago

can you share the code link

@sahilmund6824
11 months ago

Could u please share the code link