13

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

5 Answers 5

17

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();
}
10
  • hmm, I get an undefined when I run console.log(io.sockets.connected[socket.id]) any idea?
    – rwxes
    Jun 28, 2014 at 8:12
  • It means that either this socket is disconnected already, or socket.id value is invalid. What do you get if you run console.log(socket.id);?
    – Oleg
    Jun 28, 2014 at 8:14
  • I tested my solution with Socket.IO 1.0
    – Oleg
    Jun 28, 2014 at 8:17
  • socket.id works as expected returning BGGkTQOOBJTcO2YukQLl etc.. - just checked and I'm using 0.9.16, I'll try with 1.0
    – rwxes
    Jun 28, 2014 at 8:24
  • running into all sorts of other errors trying my pre-1.0 code running on 1.0 (sort of expected that). I find it strange how hard it is for me to disconnect a client by the clients socket.id yet so simple in general to setup sockets.io.
    – rwxes
    Jun 28, 2014 at 8:38
5

This is an old question but if anyone wonders for newer versions;

In Socket.IO v4.X io.sockets.connected[socket.id] or io.sockets.sockets[socket.id] is not working.

So we need to do like this;

io.sockets.sockets.forEach((socket) => {
    // If given socket id is exist in list of all sockets, kill it
    if(socket.id === givenSocketID)
        socket.disconnect(true);
});
1
  • 1
    io.sockets.sockets.get(socketId) worked for me. V4.7.2
    – refresh
    Aug 7, 2023 at 15:52
4

Alternate solution In Socket.IO v4.X

For all sockets

const sockets = await io.fetchSockets();

For particular socket

const sockets = await io.in(theSocketId).fetchSockets();

Iterate sockets

for (const socket of sockets) {
     console.log("socket id",socket.id);
     socket.disconnect(true);
}

Reference link

2
  • Would io.in(theSocketId).fetchSockets ever return multiple sockets? Jun 13, 2021 at 16:56
  • No it will return one only, loop can be removed Jun 30, 2021 at 12:14
4

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.

2
  • it didn't worked for me, it returns undefined Jun 30, 2021 at 12:19
  • 3
    Nice and clean. Worked perfectly
    – Arijit
    Jul 27, 2021 at 6:32
0

Server:

var users = {};
socket.on("identify", (username, id) => {
  eval("users." + username + " = " + '"' + socket.id + '"')
});
socket.on("getId", (username) => {
  console.log(eval("users." + username))
});
socket.on("kick", (username) => {
  io.sockets.sockets.forEach((socket) => {
    if(socket.id === eval("users." + username))
        socket.disconnect(true);
});
})

Client:

const username = prompt("What Is Your Name?")
socket.emit("identify", username)

Description: When the client enters the web page they get asked what their name is then it sends the name to the server then the server gets the id of the client and stores the name in the opject 'Users' and gives it a value of the id 'users.name = the user's socket.ID' then when you write in the console on the client side 'socket.emit("kick", username of the user)' it disconnects that user from the socket so they can't chat anymore until they reload so it pretty much kicks them from the chat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.