Node.js - Get list of all connected clients IP Add

2019-09-01 07:59发布

问题:

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.

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.

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

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.

回答1:

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