2021年3月12日星期五

Duplicate events in socket.io

Ok, so I'm trying to set up a simple chat application. When a user connects to the server, they join the chatroom. When a message is sent to the chatroom, it is broadcasted to all users. The problem I am having is that recipients receive messages twice. Consider the following example:

personimtalkingto: Hello
me: Hello
me: Hello

Client code for connecting to server:

useEffect(() => {          if(selectedConversation) {              const newSocket = io(                  'http://localhost:5000',                  {query: {'id':selectedConversation._id}}              )              setSocket(newSocket)                    return () => newSocket.close()          }      }, [selectedConversation])  

Client code for receiving message:

    useEffect(() => {          if( socket==null ) return                    socket.on('receive-message', function({chatId, msg}) {              console.log(msg)              setConversations((prevConversations => {                  for(let i = 0;i < prevConversations.length;++i) {                      if(prevConversations[i]._id === chatId) {                          prevConversations[i].messages.push(msg)                             return [...prevConversations]                      }                  }                    return [...prevConversations]              }))            })                    return () => socket.off('receive-message')      }, [socket])  

Server code:

io.on('connection', socket => {      const id = socket.handshake.query.id      socket.join(id)            socket.on('send-message', ({chatId, msg}) => {          socket.broadcast.to(id).emit('receive-message', {chatId, msg})      })  })    

Users are part of a conversation object which has a unique ID, so whenever a client connects to the server I join that socket to a room corresponding to that ID.

https://stackoverflow.com/questions/66609464/duplicate-events-in-socket-io March 13, 2021 at 10:04AM

没有评论:

发表评论