2

我的服务器正确地发出事件,但发出回调永远不会起作用。在下面,我的控制台上没有记录任何内容:

服务器:

io.sockets.emit('delete hint', {id: id}, function(data){
                    console.log('callback');
                });

客户:

socket.on('delete hint', function(data){
    // display a message before deleting
    $('#' + data.id).fadeOut(function(){ 
        $(this).remove();
    });
});

我还尝试将客户端代码作为函数(数据,fn),以防回调需要包含在接收函数中。

我正在使用 Windows,当 socket.io 发出事件时,我的命令提示符显示以下内容:

websocket writing 5:::{"name":"delete hint", "args":[{"id":"1"}, null]}

我无法弄清楚问题是什么,我做错了什么?

4

2 回答 2

5

当接收方计算机调用它时,在发送方计算机上执行回调

看看这段代码:

服务器:

io.sockets.on('connection', connectionFunc);

function connectionFunc (socket) {
    socket.emit('delete hint', "data for client", callThis);
}

//this function is executed when client calls it
function callThis (dataFromClient){

    console.log("Call back fired: " + dataFromClient);
}

客户:

    socket.on('delete hint', function(data, callback) {

        console.log("i received: "+ data);
        // call back will fire only when u the next line runs
        callback("the callThis function on server will run");            

    });

您可以以相反的方式执行此操作。

于 2014-02-21T03:58:17.743 回答
1

您需要调用回调。

socket.on('delete hint', function(data, cb){
    // display a message before deleting
    $('#' + data.id).fadeOut(function(){ 
        $(this).remove();
        cb(null, 'done');
    });
});
于 2013-03-24T19:44:20.603 回答