17

I've been looking through the entire Socket.IO docs, but, even though they promise it is there, I can't find a simple, minimal example, of how one would send binary data between server/client.

How is it done?

MaiaVictor
  • 51,090
  • 44
  • 144
  • 286
  • [Here](http://stackoverflow.com/a/24124966/2600208) is an example of how to send image as a buffer from the server and render it on an HTML5 Canvas on a client. – Oleg Jun 10 '14 at 06:03
  • @Viclib Did you got this done ? please share..!!! – H. Mahida Aug 08 '14 at 12:18
  • Ah, I have, I've forgotten how at this point, sorry for not updating. But as far as I remember, all you have to do is to get a buffer from a Float32Array (or similar) (something like that: `myData = new Float32Array([1,2,3,4]).buffer;` and sending that via `socket.io`, ie, `socket.emit("foo",myData)`. It automatically treats it as binary data. Then, on the other end, you have to convert it back: `socket.on("foo",function(data){ data = new Float32Array(data); })`. I've written that by memory, though, but I remember there was an example on the blog post about the release of `socket.io` 1.0. – MaiaVictor Aug 09 '14 at 01:59

2 Answers2

15

It is in fact in the documentation. The current documentation for Socket.io says under Socket.emit:

[...] Emits an event to the socket identified by the string name. Any other parameters can be included. All datastructures are supported, including Buffer [...]

So, if you can send a buffer, you can send binary data. All you have to do is to pack your data into a Buffer object.

You may want to read Socket.io Binary Support and Sending and Receiving Binary

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
  • 4
    Ah, that is what I was missing, then. I was searching it wrong. It is automatic, then? If I send a Float32Array it will just go as binary, instead of being serialised to JSON? – MaiaVictor Jun 05 '14 at 23:43
3

Starting from socket.io 1.0 it is possible to send binary data. http://socket.io/blog/introducing-socket-io-1-0/

How ever the way of sending and receiving binary data is not clear in the official documentation. The only documentation is:

var socket = new WebSocket('ws://localhost');
socket.binaryType = 'arraybuffer';
socket.send(new ArrayBuffer);

I suggest you to take a look at this answer, where you can find basic example with code implementation for server and client (javascript and java too):

How to send binary data with socket.io?

The good part is that it also works on Android! (if you wish)

Cheers

Community
  • 1
  • 1
chelo_c
  • 1,739
  • 3
  • 21
  • 34