【问题标题】:Receiving and update image through websocket implemented with node.js通过node.js实现的websocket接收和更新图片
【发布时间】:2017-05-09 17:08:01
【问题描述】:

我不是程序员... 我可以在 node.js 中创建一个 websocket 应用程序,可以将图像发送到 borwser,但我的图像很少,有时会改变。 前任。 图像1.jpg 图像2.jpg 图像3.jpg 图像4.jpg 我需要在浏览器中不断更新这些图片。

我的应用现在只能使用一张图片,无需更新。 听到完整的项目:https://github.com/akoscomp/imgstream 我使用此代码发布图像:

io.sockets.on('connection', function(socket){
fs.readFile(__dirname + '/image.jpg', function(err, buf){
    //it's impossible to ebed binary data
    socket.emit('image', { image: true, buffer: buf.toString('base64') });
    console.log('image file is initialized: ' + __dirname + '/image.jpg');
});});

我可以检查文件更新,但我不能在浏览器上自动更新:

   var watch = require('node-watch');
watch('image.jpg', function(evt, filename) {
  console.log(filename, ' changed.');
});

请帮助我在 borwser 中自动更新图像。之后我可能可以将代码应用于许多图像。

【问题讨论】:

    标签: node.js websocket


    【解决方案1】:

    您可以使用以下代码更改图像后发送。

    io.sockets.on('connection', function(socket) {
      connections.push(socket);
      console.log('Connected: %s sockets connected', connections.length);
    
      // Diconnect
      socket.on('disconnect', function(data) {
        connections.splice(connections.indexOf(socket), 1);
        console.log('Disconnected %s sockets connected', connections.length);
      });
    
      fs.readFile(__dirname + '/image.jpg', function(err, buf) {
        //it's impossible to ebed binary data
        socket.emit('image', { image: true, buffer: buf.toString('base64') });
        console.log('image file is initialized: ' + __dirname + '/image.jpg');
      });
    });
    
    
    var watch = require('node-watch');
    
    watch('image.jpg', function(evt, filename) {
      if (evt === 'update') {
        fs.readFile(__dirname + '/image.jpg', function(err, buf) {
          for (var i = 0; i < connections.length; i++) {
            //it's impossible to ebed binary data
            connections[i].emit('image', { image: true, buffer: buf.toString('base64') });
            console.log('image file is initialized: ' + __dirname + '/image.jpg');
          }
        });
      }
    });
    

    您可以在https://github.com/yanalavishnu/imgstream查看完整的项目

    【讨论】:

    • 我可以为多个文件编写代码,现在我可以显示自定义数量的图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2015-03-26
    相关资源
    最近更新 更多