3

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?

Raz
  • 1,601
  • 2
  • 15
  • 23
  • Take a look at the following SO question [Is it possible to combine React Native with socket.io](http://stackoverflow.com/questions/29408492/is-it-possible-to-combine-react-native-with-socket-io). This may also be helpfull [How to actually use Socket.io in React Native](https://medium.com/@ekryski/how-to-actually-use-socket-io-in-react-native-39082d8d6172#.5mdnpzh19) – DavidDomain Sep 04 '16 at 11:37
  • @DavidDomain I tried those methods but unfortunately that's not possible with the newest version of React native. Or at least I didn't manage to get it to work. https://github.com/socketio/engine.io-parser/pull/55 – Raz Sep 04 '16 at 11:42

2 Answers2

3

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.

mdziekon
  • 3,531
  • 3
  • 22
  • 32
  • Ok, I thought that might be the case. I will try more to make Socket.io work with React Native then – Raz Sep 04 '16 at 11:45
2
ws.send(`42${ JSON.stringify(["message", { command: "register" }] }`), err => {
   if (err) console.log("err", err);
});

This code using the ws pacakge as the example.

You need to add the 42 to tell socoket.io server that you are sending message, the {command: "register"} is the data you send, the "message" is the channel that socket.io is listening on.

io.on("message", (data) => {
  console.log(data); // => {command: "register"}
});

Explain: this is the engine.io-protocol that socket.io is using. Check it's spec.

The best solution is using socket.io on both side or don't use socket.io at all.

yqrashawn
  • 413
  • 5
  • 8