我是node.js和socket.io的初学者。Socket.io从1.0开始支持二进制流,是否有一个完整的示例,特别是将图像推送到客户端并在画布中显示?谢谢
该解决方案有点复杂,但是应该可以在Chrome,Firefox和IE10 +(对于Opera和Safari不确定)中使用:
服务器端的某个位置:
io.on('connection', function(socket){ fs.readFile('/path/to/image.png', function(err, buffer){ socket.emit('image', { buffer: buffer }); }); });
这是您如何在客户端上处理它:
socket.on('image', function(data) { var uint8Arr = new Uint8Array(data.buffer); var binary = ''; for (var i = 0; i < uint8Arr.length; i++) { binary += String.fromCharCode(uint8Arr[i]); } var base64String = window.btoa(binary); var img = new Image(); img.onload = function() { var canvas = document.getElementById('yourCanvasId'); var ctx = canvas.getContext('2d'); var x = 0, y = 0; ctx.drawImage(this, x, y); } img.src = 'data:image/png;base64,' + base64String; });
只需替换yourCanvasId为您的画布ID :)
yourCanvasId