user6741031
user6741031

Reputation: 107

Socket.io emit looping

I would like to be consistent with my socket.io "hooks". I use this format below pretty consistently, and it does not appear to fall into an infinite loop.

// inside my nodejs app
socket.on('foo', function (data) { 
    socket.emit('foo'); 
}); 

It only runs once when the hook is triggered from the client side, so it appears to be safe. But why would it not go in an infinite loop in the server side ? is this by accident or design ?

Upvotes: 1

Views: 2205

Answers (1)

nerdcoder
nerdcoder

Reputation: 409

This behavior is by design, not a coincidence or accident

  • client: emit a message to server with a method
  • server: receive message from client with an event handler
  • server: send a message to client with a method
  • client: receive a message from server with an event handler

server socket receive a message from client client.socket.emit('foo',aMessage) on foo event

socket.on('foo', function (data) {
    //then server emit a message to connected clients
    //not to server this is why not go through an infinite loop
    socket.emit('foo');
});

then 'client' receive the message from server

chat.socket.on('foo', function(data){
    console.log('got new message from server...',data)
})

Upvotes: 1

Related Questions