0

我正在 node.js 中(使用 socket.io)创建一个服务器,这个特定的问题一直困扰着我最长的时间。我为套接字连接制作了一个易于扩展的处理程序,以将每个不同的连接路由到不同的函数。

... <previous code> ...
var socketHandlers = {
                        'chat':chat.onMessage,
                        'chatNameRequest':chat.onNameRequest,
                        'changeRooms':commands.onPlayerRoomChange,
                        'commandEnter':commands.onCommandEnter
                    };

io.sockets.on('connection', function (socket) {
    console.log("New client connected.");

    // add all handlers to this socket when connected
    for (var handler in socketHandlers) {
        socket.on(handler, function(data) {
            console.log("Resolved handler for " + handler + ", called function " + socketHandlers[handler]);

            // sanitize each handler before sending it to the inner functions
            // leave more specific sanitization for the inner function
            data = valid.cleanData(data);
            socket = valid.cleanSocket(socket);

            // finally send it to the inner functions
            socketHandlers[handler](socket, data);
        });
    }
});

但是,它似乎不起作用。这是服务器的控制台输出:

   debug - flashsocket received data packet 5:::{"args":{"name":"Timothy"},"name":"chatNameRequest"}
Resolved handler for commandEnter, called function function (socket, data) {
<function contents, etc>

如您所见,程序收到“chatNameRequest”请求,但它错误地将其路由到“commandEnter”。有人可以阐明这里发生了什么吗?

4

1 回答 1

0

看看你的console.log输出。套接字接收到消息commandEnter,并将其路由到正确的处理程序。发布客户端代码?

此外,正如 Pointy 提到的,您应该查看.bindhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind),因为您可能很快就会需要它。

于 2014-01-29T20:03:23.420 回答