Node.js Express Project to Build P2P Webcam Live Streaming With WebSockets and Base64 Images String in Browser Using Javascript Full Project For Beginners

 

 

webcam-base64-streaming

Webcam live streaming with WebSockets and Base64

Instalation

npm install

Usage

npm run start
  • Go to /streamer
  • Allow brower to access webcam
  • Go to /client and a live feed will appear

 

 

 

index.js

 

 

const path = require('path');
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

const wsServer = new WebSocket.Server({ server: httpServer });

// array of connected websocket clients
let connectedClients = [];

wsServer.on('connection', (ws, req) => {
    console.log('Connected');
    // add new connected client
    connectedClients.push(ws);
    // listen for messages from the streamer, the clients will not send anything so we don't need to filter
    ws.on('message', data => {
        // send the base64 encoded frame to each connected ws
        connectedClients.forEach((ws, i) => {
            if (ws.readyState === ws.OPEN) { // check if it is still connected
                ws.send(data); // send
            } else { // if it's not connected remove from the array of connected ws
                connectedClients.splice(i, 1);
            }
        });
    });
});

// HTTP stuff
app.get('/client', (req, res) => res.sendFile(path.resolve(__dirname, './client.html')));
app.get('/streamer', (req, res) => res.sendFile(path.resolve(__dirname, './streamer.html')));
app.get('/', (req, res) => {
    res.send(`
        <a href="streamer">Streamer</a><br>
        <a href="client">Client</a>
    `);
});
httpServer.listen(PORT, () => console.log(`HTTP server listening at http://localhost:${PORT}`));

 

 

streamer.html

 

 

<html>
<head>
    <title>Streamer</title>
</head>
<body>
    <video autoplay></video>
    <script>
        // get video dom element
        const video = document.querySelector('video');
        
        // request access to webcam
        navigator.mediaDevices.getUserMedia({video: {width: 426, height: 240}}).then((stream) => video.srcObject = stream);
        
        // returns a frame encoded in base64
        const getFrame = () => {
            const canvas = document.createElement('canvas');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvas.getContext('2d').drawImage(video, 0, 0);
            const data = canvas.toDataURL('image/png');
            return data;
        }
        const WS_URL = location.origin.replace(/^http/, 'ws');
        const FPS = 3;
        const ws = new WebSocket(WS_URL);
        ws.onopen = () => {
            console.log(`Connected to ${WS_URL}`);
            setInterval(() => {
                ws.send(getFrame());
            }, 1000 / FPS);
        }
    </script>
</body>
</html>

 

 

client.html

 

 

<html>
<head>
    <title>Client</title>
</head>
<body>
    <img src="">
    <script>
        // get img dom element
        const img = document.querySelector('img');
        
        const WS_URL = location.origin.replace(/^http/, 'ws');
        const ws = new WebSocket(WS_URL);
        ws.onopen = () => console.log(`Connected to ${WS_URL}`);
        ws.onmessage = message => {
            // set the base64 string to the src tag of the image
            img.src = message.data;
        }
    </script>
</body>
</html>

 

 

DOWNLOAD FULL SOURCE CODE

 

 

Leave a Reply