I am using CocoaHTTPServer
library and trying to transmit binary data to a web socket. Web socket opens successfully, and can receive strings from iOS without problem. However, when I try to send a binary data through the socket, I get a Could not decode a text frame as UTF-8
error in Chrome.
Has anyone successfully transferred binary data from iOS through web sockets? (It's a UIImage
in my case)
CocoaHTTPServer
has a sendData:(NSData *)data
method which I'm using but to no success. When I use sendMessage:(NSString *)
it works without problem (which essentially converts the NSString
to NSData
using UTF-8 encoding)
So I solved it with proper encoding/decoding.
As I understand, WebSockets
do not support binary data transfer (although I was expecting it would because some tutorials show how to, and they talk about ArrayBuffer
and Blob
as the valid data types for binary transfer, which can be set using connection.binaryType='arraybuffer'
. Maybe it's experimental yet?)
Hence, you need to convert your data into textual data before transmitting through.
In iOS,
WebSocket *socket = ...; // From CocoaHTTPServer
NSData *image_data = ...;
NSString *str_64 = [Helper base64ForData:image_data]; // Can be found at http://cocoadev.com/BaseSixtyFour
[socket sendMessage:str_64];
in JS,
connection.onmessage = function(e) {
var msg = e.data;
var img1 = document.getElementById('img1');
img1.src = 'data:image/jpeg;base64,' + msg;
}
Tested in Chrome and Safari, works like a charm