How to uniquely identify a socket with Node.js

Viewed 40855

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.

7 Answers

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;

Related