I'm making a server in node.js (with socket.io), and this specific problem has been haunting me for the longest time now. I made an easily extendable handler for socket connections to route each different connection to a different function.
... <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);
});
}
});
However, it doesn't seem to be working. This is the console output from the server:
debug - flashsocket received data packet 5:::{"args":{"name":"Timothy"},"name":"chatNameRequest"}
Resolved handler for commandEnter, called function function (socket, data) {
<function contents, etc>
As you can see, the program received a request of "chatNameRequest", but it incorrectly routed it to "commandEnter." Could someone shed some light on what is going on here?
Look at what your console.log outputs. The socket received message commandEnter, and routed it to the correct handler. Post client code?
Also, as Pointy mentioned, you should look into .bind (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind), as you will probably need that quite soon.