0

as given in Sending message to a specific ID in Socket.IO 1.0, it is possible to emit to a specific client id by using

io.to(socketid).emit('message', 'for your eyes only');

In my node.js application, I am attempting to do the same thing. Basically, when the user submits another's socket.id, the node.js backend is to send the data given to that specific socket id. While the front-end submits the request correctly to the backend, when I attempt to send the data to the id, it does not go through. The "broken" part of the code looks like this:

app.post('/send', function (req, res) {
    var post_body = req.body;

    var id = (JSON.stringify(post_body.id)).split('"')[1].split('"')[0];
    var payload = JSON.stringify(post_body.payload);
    var user = JSON.stringify(post_body.user);
    
    console.log(id); 
    console.log(payload);
    console.log(user);   

    io.to(id).emit('testerEvent', { description: 'A custom event named testerEvent!'});

    res.status(200);

});

which is responding to the posted data (data is posted correctly). The client listens for the event 'testerEvent' as follows:

socket.on('testerEvent', function(data){document.write(data.description)});

When the event testerEvent is fired with just io.emit, and not io.to(id).emit, it works fine. I would appreciate any help on this, as I am just beginning to learn node and socket.io

1 Answers1

1

io.to(id) will send a message to clients that joined a room, so if you have not joined any clients to a room you won't receive the message on a client. To resolve the problem you may try to do client.join(id) when you receive a client socket from Socket.io.

Ayzrian
  • 2,279
  • 1
  • 7
  • 14
  • Thanks! Is there any way to emit it to a certain socket.client.id without using rooms? – Finn_Lancaster May 26 '21 at 13:25
  • I checked the docs, it should be joining this room by default. Are you sure that you are passing the right ID? – Ayzrian May 26 '21 at 13:29
  • The id is gotten from the client via myId = socket.io.engine.id, which is then communicated to the server by the post request. On another tab, using io.to(the id generated and sent).emit... from the server to the first tab doesn't result in anything. – Finn_Lancaster May 26 '21 at 13:32
  • If you want to send a message to the client, you need to use `socket.id` and this `socket` should be a client's socket. – Ayzrian May 26 '21 at 13:38
  • https://socket.io/docs/v4/server-socket-instance/ here you can see an example. – Ayzrian May 26 '21 at 13:39
  • Wow! I used socket.id and then realised that an alert() called at the POST request broke it! Thanks so much! – Finn_Lancaster May 26 '21 at 13:44