Issue with sending buffer over Socket.IO

2019-06-21 11:43发布

I'm trying to send a Buffer to my browser over socket.io. Supposedly this is supported as of 1.0.

Server code:

var tempBuffer = new Buffer(10);
for (var i=0; i<10; i++) {
    tempBuffer[i] = i;
}
io.sockets.emit('updateDepth', { image: true, buffer: tempBuffer });

Client code:

socket.on('updateDepth', function(data) {
    console.log("update depth: " + data.buffer + ", " + data.buffer.length);
});

Everything looks good on the client side except that data.buffer is an ArrayBuffer (not a Buffer) and the length is undefined (the ArrayBuffer does not seem to contain anything).

Am I missing something obvious or is this not how it is supposed to work? Many Thanks!

2条回答
闹够了就滚
2楼-- · 2019-06-21 12:09

Buffer is a node thing which browsers do not have native support for, but they do support Typed Arrays (better than a Buffer shim). So it makes sense to use a better container on the browser side.

查看更多
冷血范
3楼-- · 2019-06-21 12:15

Turns out this was working fine. For some reason the Buffer didn't allow me to access it directly and it's length was undefined. Converting it to a Uint8Array worked perfectly though. I'm guessing that this is because even though socket.io will now send Buffer objects there is no guarantee that your client-side javascript will know what to do with them.

This does work:

socket.on('updateImg', function(data) {
    var imgArray = new Uint8Array(data.buffer);
    console.log("update img: " + data.buffer + ", " + data.buffer.length);
});
查看更多
登录 后发表回答