0

I have this snippet on my client script:

socket.on('bla', function(data) {
    if (data == ID) {
        console.log('What the hell is happening?');
    }
})
socket.on(ID, function(data) {
    console.log('here:');
    console.log(data);
    console.log(ID);
});

And this snippet on my server script:

io.sockets.emit('bla', pairs[pairs.length-1][0].ID);
io.sockets.emit(pairs[pairs.length-1][0].ID, 'go');

This results in the client console outputting

What the hell is happening?

but not outputting anything else. Which means that pairs[pairs.length-1][0].IDon the server does equal ID on the client, but for some reason when I use them as a socket message name, it fails to match...

Ivan
  • 34,531
  • 8
  • 55
  • 100
Randomdude
  • 101
  • 2
  • 9
  • is the ID a string? I am assuming the socket event name needs to be a string. – Andrew Lohr Jul 11 '18 at 16:45
  • Yes, ID is a string. – Randomdude Jul 11 '18 at 16:47
  • if you do `if(data === ID) {` does your bla test still print `'What the hell is happening?'` – Andrew Lohr Jul 11 '18 at 16:49
  • Yes, it does!! This is so frustrating...... – Randomdude Jul 11 '18 at 16:50
  • any reason you are trying to do a dynamic event name to begin with? It usually makes life harder for the receiving end. Why not just use a static event name like bla? – Andrew Lohr Jul 11 '18 at 16:52
  • Because I only want a single client to receive that message, not all clients listening to 'bla'... only a single client has access to their ID. – Randomdude Jul 11 '18 at 16:55
  • You should look into sending the message using the sockets id (only sending to a specific client) This thread and answer can help https://stackoverflow.com/a/27270604/1309377 – Andrew Lohr Jul 11 '18 at 16:59
  • I don't want that because socket IDs can be hacked/intercepted, meaning that a hacker could easily listen to messages not meant for them, while the user ID is generated in the server and sent to the client connection... plus, socket.id is also a variable and I will encounter the same problem eventually if I don't figure out why it's happening........... it is so infuriating, because there is absolutely NO reason whatsoever that this doesn't work!! – Randomdude Jul 11 '18 at 17:02

2 Answers2

0

Have you tried to swap listeners? Just, place the second one to the first place.

Also, check, comment first emit.

0

I figured it out. I had to move the whole 'socket.on(ID, ....) inside the function that is activated once the client receives their ID from the server sockets. Otherwise, ID is undefined when that line is executed and therefore the event listener listens to undefined... instead of the client's actual ID. Thanks to everyone for trying to help.

Randomdude
  • 101
  • 2
  • 9