node.jssocket.iodisconnect

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);
};

Solution

  • The following code works with Socket.IO 1.0, however I'm not sure that this is the best solution:

    if (io.sockets.connected[socket.id]) {
        io.sockets.connected[socket.id].disconnect();
    }
    

    Update:

    With Socket.IO 0.9 the code would be slightly different:

    if (io.sockets.sockets[socket.id]) {
        io.sockets.sockets[socket.id].disconnect();
    }