Search code examples
node.jssocketsnpmtcptcpsocket

How to Get TCP Socket Id When it's connect to server


My question is, How to Get TCP Socket Id When it's connect to server.

I have code like this,

const net = require('net');

const server = net.createServer();
server.listen(port, host, async() => {
    console.log('Server is running on port 6633');
});

server.on('connection', async function(sock) {

   console.log('sockId: ',sock.id); // It's give me undefined

}

So, How to Get Socket Id in TCP Connection in NodeJS.


Solution

  • for my own particular need when addressing this, I just created a map with some user identifier and the websocket itself.

    otherwise you can use the request header req.headers['sec-websocket-key']

    let socketMap = new Map()
    server.on('connection', async function(sock, req) {
       console.log('sockId: ',sock.id); // It's give me undefined
       socketMap.set(req.headers['sec-websocket-key'], sock)
    }