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.
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);
};
Here's another option for Socket.IO v4 that doesn't require async syntax:
io.sockets.sockets.get(socket.id)
Someone can correct this if it's wrong, but I think each socket has a unique ID, so there should be no need for iterating.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With