简体   繁体   中英

Binary data from iOS to WebSockets

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

Beware encoding to base64 is the easy but not necessary the right solution performace wise, you are putting unnecessary processing of encoding and decoding . There is a livio which is a fork from CoccoaHTTPServer, but it implements the websocket binary send. I dont understand why its is not a plull request, and why it is not mereged into coccoapod, so u need to use Carthage instead of coccoapod.

But as of right now https://github.com/livio/LivioHTTPServer seems to be the answer/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM