Raz
Raz

Reputation: 1710

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?

Upvotes: 3

Views: 3822

Answers (3)

Atharv Andewar
Atharv Andewar

Reputation: 1

Socket.io used socket.io and engine.io protocol hence we need to follow messaging pattern according to these protocols

  • 40: Open connection
  • 42: Indicates a message containing an event

Hence, Your first message needs to be

40

and then for your socket.io events message should be

42["eventName", "stringData"]

If you receive ping from websocket i.e 2 you will have to response with pong i.e. 3

You can read up https://socket.io/docs/v4/socket-io-protocol/

Upvotes: -3

yqrashawn
yqrashawn

Reputation: 423

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.

Upvotes: 2

mdziekon
mdziekon

Reputation: 3627

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.

Upvotes: 4

Related Questions