javascriptwebsocketsocket.ioreact-native

How to send a message with WebSocket to a Socket.io server


I'm developing a React Native application and I want to use the WebSocket class to communicate with my Socket.io server.

I can connect to the server just fine, but I'm having problems sending messages to it using the .send() method.

I tried this on React Native:

var socket = new WebSocket("ws://host:port/socket.io/?transport=websocket");
socket.onopen = () => {
    console.log("connected");
    socket.send('data');
 };

On my Socket.io server I have this listener that I created just for testing:

socket.on('data', function(data) {
  console.log("data");
})

The connection does work, and I'm able to see that on the server too. But when I do socket.send('data') the disconnect event gets called on the server rather than the data event I wrote above. (I tested this by using a function to call the .send() method, so this does cause a disconnect on the server)

Can anyone shine some light on this?


Solution

  • That's because Socket.io is not exactly compatible with WebSocket - there are initial handshakes, connection fallbacks (eg. when no WS is available, use AJAX long pooling or other technique) and other things that Socket.io hides from you to make your life easier. Essentially, Socket.io should be seen as a separate protocol.

    To connect to a Socket.io server, you have to use Socket.io client library.