Max Turner
Max Turner

Reputation: 156

React Native websocket event.data is empty array when receiving binary data

I am trying to use a websocket connection in a React Native app to receive binary data, my websocket code looks like this:

var websocket = new WebSocket("ws://10.10.10.1/stream")

websocket.onmessage = (event) => {
        console.log(event);
        console.log(event.data);

        var reader = new FileReader();
        reader.readAsText(event.data, "UTF-8");

        reader.onload = function() {
         ...
        }
}; 

The logged event object looks like:

{data: [], istrusted: false}

event.data logs as undefined

I am able to connect, and send messages normally, but not able to receive messages. I have the same websocket connection working fine in a web app, so I know the websocket server is sending correct data, but for some reason I am not able to get the incoming message data when using React Native.

Is there something specific with how React Native is handling this?

Upvotes: 1

Views: 2167

Answers (1)

Max Turner
Max Turner

Reputation: 156

Posting here because I found a solution to my problem.

The above code works in React or regular javascript webpage, but in react native I had to add this line to specify the binaryType as 'blob'

var websocket = new WebSocket("ws://10.10.10.1/stream");
websocket.binaryType = 'blob';

Hopefully this helps someone else with the same problem later on

Upvotes: 6

Related Questions