io.sockets.emit错误广播js脚本时不支持回调

时间:2018-11-04 01:20:42

标签: javascript node.js nodes

当我用nodejs启动我的js脚本时,我得到了错误:

/var/www/html/bot/node_modules/socket.io/lib/namespace.js:224
    throw new Error('Callbacks are not supported when broadcasting');
    ^

Error: Callbacks are not supported when broadcasting
    at Namespace.emit (/var/www/html/bot/node_modules/socket.io/lib/namespace.js:224:11)
    at Object.<anonymous> (/var/www/html/bot/driver.js:307:14)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

发生脚本的部分:

    io.sockets.emit('disconnect', function() {
    var index = -1;
    if(users[user.steamid])
    index = users[user.steamid]['socket'].indexOf(socket.id);
    if (index > -1) {
        users[user.steamid]['socket'].splice(index, 1);
    }
    if(users[user.steamid]) { if(Object.keys(users[user.steamid]['socket']).length == 0) delete users[user.steamid]; }
  });

您能告诉我出什么问题并向我解释错误吗?

1 个答案:

答案 0 :(得分:0)

我看到您想向所有套接字发送disconnect事件(您想要什么???)。 emit函数只有2个参数(event_namedata),在代码中,您将函数作为第二个参数(而不是data对象)。

但是,我认为您的逻辑是在检测到套接字断开连接时移除用户hmmm

查看此处:

io.sockets.on('connection', function (socket) {
    socket.on('disconnect', function () {
        var index = -1;
        if (users[user.steamid])
            index = users[user.steamid]['socket'].indexOf(socket.id);
        if (index > -1) {
            users[user.steamid]['socket'].splice(index, 1);
        }
        if (users[user.steamid]) { if (Object.keys(users[user.steamid]['socket']).length == 0) delete users[user.steamid]; }
    });
});