Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with sending buffer over Socket.IO

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!

like image 829
Joel Avatar asked Oct 21 '14 23:10

Joel


People also ask

Does Socket.IO use long polling?

js) and the Socket.IO client (browser, Node. js, or another programming language) is established with a WebSocket connection whenever possible, and will use HTTP long-polling as fallback.

Is Socket.IO good for notifications?

Socket.io is a popular JavaScript library that allows us to create real-time, bi-directional communication between clients and a Node. js server. It is a highly performant and reliable library optimized to process a large volume of data messages with minimal delay.

Which is better Socket.IO or WebSockets?

Both WebSocket vs Socket.io are popular choices in the market; let us discuss some of the major Difference Between WebSocket vs Socket.io: It provides the Connection over TCP, while Socket.io is a library to abstract the WebSocket connections. WebSocket doesn't have fallback options, while Socket.io supports fallback.


1 Answers

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);
});
like image 186
Joel Avatar answered Oct 02 '22 03:10

Joel