I'm new to nodejs and trying to write a chat room as so many people have.
The chat consists of multiple rooms and clients. Commands such as /nick
/join
/help
/ls users
/ls rooms
work as you would expect although I'm having trouble with getting a /kick
command to work.
I'm just not sure how you disconnect a client by id, so far /kick client
is able to present the respective clients socket.id although I'm stuck for the code to kick via socket.id.
Code so far:
Disconnect client who sent /kick
: socket.disconnect();
Delete client from arg /kick client
: delete io.sockets.sockets[client];
Deleting the client doesn't disconnect them though, they can still receive data just not send it.
Solved
CuriousGuy's 0.9 worked flawlessly, for those interested - here is the code I'm using.
Server side:
handleClientKick(socket);
...
function handleClientKick(socket) {
socket.on('kick', function(client) {
if (typeof io.sockets.sockets[client] != 'undefined') {
socket.emit('message', {text: nickNames[socket.id] + ' kicked: ' + nickNames[client]});
io.sockets.sockets[client].disconnect();
} else {
socket.emit('message', {text: 'User: ' + name + ' does not exist.'});
}
});
}
Client side:
kickClient = function(client) {
this.socket.emit('kick', client);
};
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…