Streaming image/video with socket.io-stream and nodejs

1k views Asked by At

I want to send a picture to the front using socket.io-stream but the browser does not enter the stream event .on('data' ) but enters the event .on('end')

why is that? and in addition - I want to finally add the code so that I can do live streaming of the video, just for now I'm trying to stream the image file

server

const express = require('express');
const { Server } = require("socket.io");
const http = require('http');
const fs = require('fs');

const app = express();
app.use(express.static("public"));
const server = http.createServer(app);
const io = new Server(server);
const ss = require('socket.io-stream');

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

// входящее сообщение, что клиент присоединился
// подхватываем сокет клиента
io.on('connection', (socket) => {
  console.log('user connect');

  setTimeout(() => {
    let ssStream = ss.createStream();
    ss(socket).emit('image', ssStream, 'log')
    fs.createReadStream('/Users/artem/Work/dataset/frame000023.png').pipe(ssStream);
  }, 1000)

 
})
server.listen(3000, () => {
  console.log('listening on *:3000');
});

client

const socket = io();

      ss(socket).on('image', function(stream,data) {
        console.log('received',data);

        var binaryString = "";

        stream.on('data', function(data) {
          console.log('data')

          for(var i=0;i<data.length;i++) {
            binaryString+=String.fromCharCode(data[i]);
          }

        });

        stream.on('end', function(data) {
          console.log('end')
       $("#img").attr("src","data:image/png;base64,"+window.btoa(binaryString));

          binaryString = "";
        });
      });
0

There are 0 answers