Skip to content
Advertisement

Why does the sender message only appear when the recipient sends a message? (socketio) (nodejs) (reactjs)

I am developing a realtime chat in nodejs and react and socket io. In theory the chat is working, but the problem is that the sender’s message only appears on the screen when the recipient sends a message too.

ex : I have browser 1 and browser 2. Every time browser 1 sends messages, these messages appear on its screen, but these messages only appear for browser 2 when browser 2 sends a message.

JavaScript

react/socketio

JavaScript

Advertisement

Answer

You’re using

socket.emit('message-from-server', messages);

Try using io.emit instead, which broadcasts to all attached sockets. Socket.emit is used to send a message only to the called socket. In this case, that means the socket that first sent the message. This can be helpful for if you just want to notify that individual socket that something processed correctly, etc., but it isn’t useful for when you want to notify other users of a socket’s actitivies.

EDIT: Here’s a link to the docs that describe your various emit options: https://socket.io/docs/v4/broadcasting-events/

Here’s what your server-side code should look like:

JavaScript

Note the difference between the io.emit that I use in the listener and the socket.emit that I use when first connecting.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement