我正在 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”。有人可以阐明这里发生了什么吗?