Abhishrek Abhishrek - 2 months ago 13
HTML Question

How to uniquely identify a socket with Node.js

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.


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