Socket.io 通过 id 断开客户端 [英] Socket.io disconnect client by id

查看:124
本文介绍了Socket.io 通过 id 断开客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 nodejs 的新手,并试图像很多人一样编写一个聊天室.聊天由多个房间和客户组成./nick /join /help /ls users /ls rooms 等命令尽管我在使用 /kick 命令时遇到问题,但它可以按您的预期工作.

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.

我只是不确定您如何通过 id 断开客户端的连接,到目前为止 /kick client 能够显示相应的客户端 socket.id,尽管我被代码困住了套接字.id.

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.

到目前为止的代码:

断开发送/kick的客户端:socket.disconnect();

Delete client from arg /kick client: delete io.sockets.sockets[client];

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 的 0.9 完美无缺,对于那些感兴趣的人 - 这是我正在使用的代码.

CuriousGuy's 0.9 worked flawlessly, for those interested - here is the code I'm using.

服务器端:

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

客户端:

kickClient = function(client) {
  this.socket.emit('kick', client);
};

推荐答案

以下代码适用于 Socket.IO 1.0,但我不确定这是最佳解决方案:

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

更新:

使用 Socket.IO 0.9 时,代码会略有不同:

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

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

这篇关于Socket.io 通过 id 断开客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆