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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With