How to uniquely identify a socket with Node.js


Question

TLDR; How to identify sockets in event based programming model.

I am just starting up with node.js , in the past i have done most of my coding part in C++ and PHP sockets() so node.js is something extremely new to me.

In c++ to identify a socket we could have done something like writing a main socket say server to listen for new connections and changes, and then handling those connections accordingly.

1
16
3/1/2015 7:21:22 PM

Accepted Answer

If you are looking for actual sockets and not socket.io, they do exist.

But as stated, Node.js and Javascript use an event-based programming model, so you create a (TCP) socket, listen on an IP:port (similar to bind), then accept connection events which pass a Javascript object representing the connection.

From this you can get the FD or another identifier, but this object is also a long-lived object that you can store an identifier on if you wish (this is what socket.io does).

var server = net.createServer();

server.on('connection', function(conn) {
  conn.id = Math.floor(Math.random() * 1000);
  conn.on('data', function(data) {
    conn.write('ID: '+conn.id);
  });
});
server.listen(3000);
19
7/24/2011 5:26:58 PM

Timothy's approach is good, the only thing to mention - Math.random() may cause id's duplication. So the chance it will generate the same random number is really tiny, but it could happen. So I'd recommend you to use dylang's module - shortid:

var shortid = require('shortid');
var server = net.createServer();

server.on('connection', function(conn) {
  conn.id = shortid.generate();
  conn.on('data', function(data) {
    conn.write('ID: '+conn.id);
  });
});
server.listen(3000);

So in that case you can be sure that no id duplications will occur.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon