How to uniquely identify a socket with Node.js

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

in typescript:

import { v4 as uuidv4 } from 'uuid';
import net from 'net';
class Socket extends net.Socket {
  id?: string;
}

const server = net.createServer();

server.on('connection', (conn) => {
  conn.id = uuidv4();
  conn.on('data', (data) => {
      console.log(conn.id);
  });
});
server.listen(3000);

you need to add id first;


In c++ to identify a socket we could have done something like writing a main socket say server to listen for new connections and then handling those connections accordingly.but so far i havent found anything like that in node.js . (the berkeley socket model) Does it even exist in node.js .. if not i am going back to my C++ :$

You should go back, because JavaScript is a prototype-based, object-oriented scripting language that is dynamic, weakly typed and has first-class functions. They are both completely different languages and you will have to have a different mindset to write clean JavaScript code.

https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7

Session ID

If you made use of the sessionId property of socket in v0.6, this is now simply .id.

// v0.6.x
var sid = socket.sessionId;

// v0.7.x
var sid = socket.id;

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.