通过使用node.js实现的websocket接收和更新图像
问题描述:
我不是程序员... 我可以在node.js中创建一个websocket应用程序,它可以将图像发送到borwser,但是我会有几张图像,有时会改变。例如, image1.jpg image2.jpg image3.jpg image4.jpg 我需要在浏览器中更新此图像。通过使用node.js实现的websocket接收和更新图像
我的应用程序现在只适用于一个图像,没有更新。 整个项目是听到: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.');
});
请帮助我自动执行映像更新。之后,我可能可以应用许多图像的代码。
答
使用以下代码更改图像后即可发送图像。
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');
}
});
}
});
感谢检查完整的项目。这行得通。 – Akos
我可以为多个文件编写代码,现在我可以显示自定义数量的图像。 – Akos