socket io,node js,简单示例从服务器发送图像/文件到客户端
有没有关于如何提供图像的简单明了的例子? 从服务器到客户端? 通过缓冲或只是一个直接的电话下载? (目标是有效地近乎实时地获取图像文件,以便呈现近乎直播的图像stream),并附加到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? } });
感谢您的阅读
更新:
从下面的代码片段后,它也需要将“缓冲区”variables更改为image.buffer为了图像正确显示
基本上改变了路线
img.src = 'data:image/jpeg;base64,' + buffer;
至
img.src = 'data:image/jpeg;base64,' + image.buffer;
一个可能的解决scheme是对图像数据进行64位编码,并通过image.src
在浏览器中使用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); } });