Socket.IO的奇怪问题

时间:2012-11-26 19:04:09

标签: node.js socket.io

我对Socket.IO有一个非常奇怪的问题。出于某种原因,看起来发射“缓冲区”一遍又一遍地重复,因为每个连接都会产生n + 1个回复:

COM.ping();
undefined
0 "CONNECTION STATUS: OK - 0" app.js:9
COM.ping();
undefined
1 "CONNECTION STATUS: OK - 1" app.js:9
2 "CONNECTION STATUS: OK - 1" app.js:9
COM.ping();
undefined
3 "CONNECTION STATUS: OK - 2" app.js:9
4 "CONNECTION STATUS: OK - 2" app.js:9
5 "CONNECTION STATUS: OK - 2" app.js:9
COM.ping();
undefined
6 "CONNECTION STATUS: OK - 3" app.js:9
7 "CONNECTION STATUS: OK - 3" app.js:9
8 "CONNECTION STATUS: OK - 3" app.js:9
9 "CONNECTION STATUS: OK - 3" app.js:9
COM.ping();
undefined
10 "CONNECTION STATUS: OK - 4" app.js:9
11 "CONNECTION STATUS: OK - 4" app.js:9
12 "CONNECTION STATUS: OK - 4" app.js:9
13 "CONNECTION STATUS: OK - 4" app.js:9
14 "CONNECTION STATUS: OK - 4" app.js:9

这个代码非常简单。在客户端:

    this.ping = function(){
        socket.on('PING__',function (data){
            console.log(count++,"CONNECTION STATUS: "+$(data)[0].status);
            data = '';
        });
        socket.emit('__PING');
    }

在服务器上:

    var counter = 0;
    io.sockets.on('connection', function (socket) {
        socket.on('__PING', function (data) {
            socket.emit('PING__' , {status:'OK - '+counter++});
        });
    });

因此,出于某种原因,当我尝试ping时,它在某种程度上重申了。我不知道为什么。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

想出来。真是愚蠢的逻辑错误:

 this.ping = function(){
        socket.on('PING__',function (data){
            console.log(count++,"CONNECTION STATUS: "+$(data)[0].status);
            data = '';
        });
        socket.emit('__PING');
    }

应该是:

var events = {};
this.ping = function(){
    if(typeof events.ping === 'undefined'){
        events.ping = socket.on('PING__',function (data){
            console.log("CONNECTION STATUS: "+$(data)[0].status);
            data = '';
        });
    }
    socket.emit('__PING');
}

它搞得一团糟,因为我一遍又一遍地绑定事件处理程序。