Node.js-获取所有连接的客户端IP地址的列表? [英] Node.js - Get list of all connected clients IP Addresses?

查看:67
本文介绍了Node.js-获取所有连接的客户端IP地址的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个聊天应用程序,我希望监视哪些用户在线以及哪些用户离开了.当用户加入Connect时,它将把他的IP以及用户名等添加到mysql用户在线表中.当用户离开断开连接"时,它将从用户在线上删除其IP.

I am making a chat application, I wish to monitor which users are online and which have left. When user joins on Connect it will add his IP to mysql users online table along with username etc.. When user leaves on Disconnect it will remove his IP from users online.

以防万一发生任何无法预料的情况,我想获取当前已连接到服务器的客户端的所有IP地址,并将其与表中的IP地址进行比较,以这种方式对连接的客户端和未连接的客户端进行排序.

Just in case any unpredicted scenario happens, I want to get all IP addresses of clients that are currently connected to server and compare it to the ones that are in table and that way sort which clients are connected and which aren't.

那么我如何获得已连接客户端的IP列表?

So how can I obtain a list of ip's of connected clients?

我之所以要使用MySQL和表格是因为我想监视当前有多少用户从外部PHP站点在线.如果有更好的方法,我欢迎您提出建议.

The reason I want to use MySQL and table for this is because I want to monitor how many users are currently online from external PHP site. If there is better way I am open for suggestions.

推荐答案

一种解决方案是保留一个包含所有已连接套接字的对象(在connect上添加,在close上删除).然后,您只需遍历对象中的套接字即可.

One solution would be to keep an object around that contains all connected sockets (adding on connect and removing on close). Then you just iterate over the sockets in the object.

或者,如果您喜欢冒险,可以使用未记录的方法来获取节点中所有活动的句柄并对其进行过滤.示例:

Or if you're feeling adventurous, you could use an undocumented method to get all of the active handles in node and filter them. Example:

var http = require('http');

var srv = http.createServer(function(req, res) {
  console.dir(getIPs(srv));
  // ...
});
srv.listen(8000);

function getIPs(server) {
  var handles = process._getActiveHandles(),
      ips = [];

  for (var i = 0, handle, len = handles.length; i < len; ++i) {
    handle = handles[i];
    if (handle.readable
        && handle.writable
        && handle.server === server
        && handle.remoteAddress) {
      ips.push(handle.remoteAddress);
    }
  }

  return ips;
}

这篇关于Node.js-获取所有连接的客户端IP地址的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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