Twois
Twois

Reputation: 598

node js net library - get info about the client(socket)

I use nodejs cluster with socket.io, and in the master thread I use the built in net library to listen on a port and pass the connection(socket) manually to the workers (based on the client's ip address, so if the client reconnect to the server the client will join to the same worker). This is working well, but I would like to test, and I want to join to different worker from localhost.

Is there any way to get info about the client (e.g. browser name, custom parameter) or anything else to make different between two or more clients from localhost? - It could be cool if I'm be able to join the client to a worker based on the browser (chrome clients goes to worker 1, firefox clients goes to worker 2) on development environment.

private createServer(): void {
    var self = this;

    this.masterServer = net.createServer(<any>{ pauseOnConnect: true }, (connection) => {
        console.log('server', connection);

        let worker = self.workers[self.getWorkerIndex(connection.remoteAddress, self.workerCount)];
        worker.send('privateCon', connection);

    }).listen(self.serverPort);
}

Upvotes: 1

Views: 1339

Answers (1)

Matt
Matt

Reputation: 74680

On Windows and Linux the entire 127.0.0.0/8 range works on the loobback interface by default so you could differentiate connections by their destination or localAddress as long as your server is not listening on one specific address.

Run a simple server

$ node -e 'net.createServer(connection => {
    console.log(connection.remoteAddress, connection.remotePort, connection.localAddress)
}).listen(8082)'

Then connect with something like telnet or nc or even node.

$ node -e 'client = net.connect(8082, "127.0.0.4", ()=> client.end())'

OSX always gets a connection mapped to IPv6 even when specifying IPv4, not sure if you will get that on Windows too, but the output from the server should read something like:

::ffff:127.0.0.4 57290 ::ffff:127.0.0.4

So you could use something for your connection handler like

switch (connection.localAddress){
  case '::ffff:127.0.0.1':  return worker1
  case '::ffff:127.0.0.2':  return worker2
  case '::ffff:127.0.0.3':  return worker3
  case '::ffff:127.0.0.4':  return worker4
  default: return lookupWorker()
}

Upvotes: 1

Related Questions