Socket.io触发多个事件

Jos*_*ing 8 websocket node.js socket.io

Socket.io似乎是以指数方式触发多个消息,这是我正在运行的一个导致问题的示例.

客户端:

<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>
Run Code Online (Sandbox Code Playgroud)

服务器端:

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

socket.on("test_child", function(){
    socket.emit("test_child_server", { data : " " });
});
Run Code Online (Sandbox Code Playgroud)

出于某种原因,每次单击按钮时,事件都会多次触发,并呈指数级增长.我试图找出发生了什么,但没有运气调试或在线搜索.

Bre*_*and 24

每次调用单击处理程序时,它都会将其他事件侦听器附加到套接字.您在之前点击时附加的听众仍然有效.您需要开始使用removeListener或removeAllListeners来删除旧的侦听器,或者您需要将侦听器代码移动到单击处理程序之外,以便不会多次调用它.

例如:

$("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");
});
Run Code Online (Sandbox Code Playgroud)