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.

4

1 回答 1

24

每次调用单击处理程序时,它都会将其他事件侦听器附加到套接字。您在之前的点击中附加的侦听器仍然处于活动状态。您要么需要开始使用removeListenerremoveAllListeners来删除旧的侦听器,要么需要将侦听器代码移到点击处理程序之外,这样它就不会被多次调用。

例如:

$("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");
});
于 2013-06-12T04:13:12.497 回答