8

Socket.io seems to be firing multiple messages exponentially, here is an example I'm running that causes the issue.

Client side:

<html> <head> <script type="text/javascript" src="../../js/jquery191.min.js"></script> <script type="text/javascript" src="http://192.168.1.2:8887/socket.io/socket.io.js"></script> </head> <body> <button>Click Me!</button> <script type="text/javascript"> $(document).ready(function(){ var socket = io.connect('http://192.168.1.2:8887'); $("button").click(function(){ console.log("Emitting test_parent"); socket.emit('test_parent'); socket.on('test_parent_server', function(data){ console.log("Handling test_parent_server"); console.log("Emitting test_child"); socket.emit('test_child'); socket.on('test_child_server', function(ing){ console.log("Handling test_child_server"); }); }); }); }); </script> </body> </html> 

Server side:

socket.on("test_parent", function(){ socket.emit("test_parent_server", { data : " " }); }); socket.on("test_child", function(){ socket.emit("test_child_server", { data : " " }); }); 

For some reason every time the button is clicked the events get fired multiple times, increasing exponentially. I've tried to pinpoint what the heck is going on but no luck debugging it or searching online.

1 Answer 1

24

Every time the click handler is called, it attaches additional event listeners to the socket. The listeners you attached on the previous clicks remain active. You either need to start using removeListener or removeAllListeners to remove old listeners, or you need to move the listener code outside the click handler so that it doesn't get called multiple times.

For example:

$("button").click(function() { console.log("Emitting test_parent"); socket.emit('test_parent'); }); socket.on('test_parent_server', function(data) { console.log("Handling test_parent_server"); console.log("Emitting test_child"); socket.emit('test_child'); }); socket.on('test_child_server', function(ing) { console.log("Handling test_child_server"); }); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I did not realize that socket.io would concatenate the callbacks like that, now that I have is structure the way you did it worked!
@JosephShering, It's not socket.io specific. It's how most event systems work. I'm glad it worked. If you're happy with my answer, please mark it as accepted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.