Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io disconnect client by id

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);
};
like image 674
rwxes Avatar asked Jun 28 '14 04:06

rwxes


1 Answers

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.

like image 66
SuperCodeBrah Avatar answered Oct 09 '22 22:10

SuperCodeBrah