【问题标题】:socket io, node js, Simple example to send image/files from server to client套接字 io,节点 js,将图像/文件从服务器发送到客户端的简单示例
【发布时间】:2014-12-07 12:48:42
【问题描述】:

是否有任何关于如何提供图片的简单直接的示例?从服务器到客户端?通过缓冲还是直接调用下载? (目标是高效地近乎实时地获取图像文件,以呈现近乎实时的图像流)并附加到 html 图像标签或仅在 html 页面的正文中。

不完整的示例代码:(大部分来自官方示例或只是来自stackoverflow的代码)

index.js

// basic variables
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var fs = require('fs'); // required for file serving

http.listen(3000, function(){
  console.log('listening on *:3000');
});

// location to index.html
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

// only to test chat sample code from sample
io.on('connection', function(socket){

  console.log('a user connected');
    // broadcast a message
  socket.broadcast.emit('chat message', 'System Broadcast Message: a user has been connected');
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });

// trying to serve the image file from the server
io.on('connection', function(socket){
  fs.readFile(__dirname + '/images/image.jpg', function(err, buf){
    // it's possible to embed binary data
    // within arbitrarily-complex objects
    socket.emit('image', { image: true, buffer: buf });
    console.log('image file is initialized');
  });
});

(客户端 html 页面) index.html(我们将只讨论提供图像的部分) 我们可以在客户端做些什么来获取文件并在 html 页面上提供图像?

  socket.on("image", function(image, buffer) {
     if(image)
     {
         console.log(" image: from client side");
         // code to handle buffer like drawing with canvas** <--- is canvas drawing/library a requirement?  is there an alternative? another quick and dirty solution?
        console.log(image);
        // what can we do here to serve the image onto an img tag?
     }

 });

感谢您的阅读


更新:

在下面的代码 sn-ps 之后 它还需要将“buffer”变量更改为 image.buffer 以使图像正确显示

基本上从

换行
img.src = 'data:image/jpeg;base64,' + buffer;

img.src = 'data:image/jpeg;base64,' + image.buffer;

【问题讨论】:

标签: javascript node.js sockets socket.io socket.io-1.0


【解决方案1】:

一种可能的解决方案是对图像数据进行base64编码,并通过image.src在浏览器中使用:

在服务器端,尝试更改:

socket.emit('image', { image: true, buffer: buf });

到这里:

socket.emit('image', { image: true, buffer: buf.toString('base64') });

然后在客户端:

var ctx = document.getElementById('canvas').getContext('2d');

// ...

socket.on("image", function(info) {
  if (info.image) {
    var img = new Image();
    img.src = 'data:image/jpeg;base64,' + info.buffer;
    ctx.drawImage(img, 0, 0);
  }
});

【讨论】:

  • 谢谢,我能够让它与您的 sn-ps 一起工作,并将变量从缓冲区更改为 image.buffer!像这样:img.src = 'data:image/jpeg;base64,' + image.buffer;谢谢!寻求帮助!
  • @mscdex 这种发送图像的 base64 方法对我有用,但在我的聊天应用程序中,每当我尝试发送超过 3 mb 且尺寸超过 1k 的大图像时,每次套接字 io断开聊天,可能是由于我的互联网上传速度慢。是否有更好且可扩展的方式将图像或文件上传到服务器并以一种可以处理大文件上传的轻量方式显示到客户端。?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 2019-08-27
  • 2016-03-03
  • 2017-05-26
相关资源
最近更新 更多