Home > Enterprise >  Socket.io Client repeats event action multiple times from one emit
Socket.io Client repeats event action multiple times from one emit

Time:04-10

I am creating a simple diffie hellman demo with sockets and it seems that whenever my server emits any event, the client repeats it multiple times.

For example: On the client side whenever I add a message I emit this new message to the server like so.

  const addMessage = (text) => {
    var newMessage = {
      id: nextID,
      from: name,
      message: text
    }
    socket.emit("send-message", newMessage);
    setNextID(nextID   1);    
    setMessages([...messages, newMessage]);
  }

And then on the server side I add that message to the messages and emit the new bank of messages to the other clients.

    // Send message to other person
    socket.on("send-message", (message) => {    
        messages = [...messages, message];
        console.log(messages, "Newline\n");
        
        socket.broadcast.emit("receive-message", messages);
    })

The clients receive it and updates their message bank. I console.log these actions.

    socket.on("receive-message", (receivedMessages) => {
      console.log("receieved messages");
      setMessages(receivedMessages);
    });

But when I send a message it console.logs it repeats it like 100 times?? enter image description here

This happens for a lot of my other client side events handlers, repeating a action more than once, from just one emit from the server.

Why does this happen and how can I stop it?

CodePudding user response:

try to change like:

client-side:

socket.emit(“your event name”, “msg”)

server-side:

var io = new require(“socket-io”)()
io.on(“connection”, (socket) => {
    socket.on(“your event name”, (msg) => {
        io.emit(“your event name”, msg)
    })
})

try it out and it will be better :D

CodePudding user response:

Just send the new message

Client

socket.on("receive-message", (receivedMessages) => {
  console.log("receieved messages");
  setMessages(prevMessage => [...prevMessage, receivedMessages]);
});

Server

socket.on("send-message", message => {    
    messages = [...messages, message];
    console.log(messages, "Newline\n");
        
    socket.broadcast.emit("receive-message", message);
})
  • Related