Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a WebSocket switch its binaryType on the fly?

In JavaScript, when you instantiate a WebSocket:

ws = new WebSocket(url);

you can set it's binaryType:

ws.binaryType = "blob";
// or
ws.binaryType = "arraybuffer";

Question: Can I change binaryType on the fly?

For example if I wanted to use the same WS instance to interleave both text and binary messages, could I do the following?

ws = new WebSocket(url);
// Send text
ws.binaryType = "blob";
ws.send("this is text");
// Now send binary data
ws.binaryType = "arraybuffer";
var ab = new ArrayBuffer(...); 
ws.send(ab);

In reading the W3C WebSocket spec, I didn't see anything that explicitly says "you can't change binaryType", but every example/usage of WebSocket that I've seen sets binaryType once then never changes it, which sorta suggests that it can't be changed.

Any info would be appreciated.

like image 417
dlchambers Avatar asked May 28 '13 20:05

dlchambers


1 Answers

You can change the binaryType on the fly, but it only affects the datatype of received messages. To send binary data you must either send a blob or a typed array. If you send a string it will always be sent (and delivered) as a string. In the wire protocol, a message can be either 'text' meaning the sender sent data encoded as a string, or it can be 'binary' which means that the message contains a raw encoded byte stream. The binaryType indicates how that raw data should be delivered to the application.

In other words, when you set binaryType it means that the next time the message handler fires for receipt of a binary message, that event data will be of type binaryType.

like image 140
kanaka Avatar answered Nov 03 '22 10:11

kanaka