Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

node.js - 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);
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...