Obtaining the TCP Socket ID Upon Establishing Connection with the Server

One question I have is, How can I retrieve the TCP Socket Id when it's connected to the server?

Here's the code snippet I am working with:

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 returns undefined

}

Can anyone advise on how to obtain the Socket Id in a TCP Connection using NodeJS?

Answer №1

When dealing with this issue, I decided to create a map containing user identifiers along with the websocket itself.

Another option is to access the request header using 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)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue creating a JWT using jsonwebtoken module in Node.js

Could someone help me troubleshoot an issue I'm having while trying to generate a JWT token? The error message "TypeError: Right-hand side of 'instanceof' is not an object" keeps appearing even though the syntax seems correct. const jsonwebt ...

Implementing authorization middleware using Express.js in Ajax

My app has a straightforward authorization middleware that functions flawlessly with regular GET and POST requests. However, when I send a POST request via AJAX, the middleware fails to redirect to a 401 page and instead bypasses it, allowing the data to b ...

Distinguishing Between Angular and Ajax When Making Requests to a NodeJS Server

Trying to establish communication between an Angular client and a NodeJS server. Previous method using JQuery $.ajax({ url: "/list", type: "POST", contentType: "application/json", dataType: "json", success: function(data) { console.log("Data ...

Having trouble with React testing-library: Why is the file upload empty when testing a PDF file?

While testing file upload with react-testing-library, I encountered an issue where the log indicated that the file was empty (even though it worked in the browser). After researching various docs and bugs, I discovered that since tests run on Node.js, the ...

Obtain ng-model data upon sending a POST request to an Express.js endpoint

I am currently developing a Node.js application that incorporates AngularJS. My goal is to execute a simple POST request using Angular. This POST request should send a set of values to my server, where I can view them using the console.log function. With ...

Having difficulty uninstalling AWS-CDK on my Linux system

I recently realized that I have AWS-CDK installed on my system, but now I'm struggling to remove it. It's been a while since I initially installed it, and I can't quite remember how I did so. However, even after attempting to uninstall it us ...

Upon transitioning from Angular 5 to Angular 6, a noticeable issue arises: The existing document lacks a required doctype

I recently updated my project from Angular 5 to Angular 6. Post-upgrade, everything compiles without errors. However, when I try to access the website, all I see is a blank screen. Upon inspecting the console, I came across the following error message: Th ...

Having trouble accessing variable values within the nth-child selector in JavaScript

I am attempting to utilize the value of a variable within the element selector p:nth-child(0). Instead of hardcoding the number as 0, I want to dynamically assign the value of a variable. In this case, the variable is represented by i in a for loop. Howev ...

Implementing Node.js microservices with AWS Cognito leveraging Amplify's best practices

I am currently working on developing a Node.js API that is broken down into several small APIs (microservices) communicating with each other through requests and responses. Additionally, I am utilizing Angular for the frontend. My next step is to enhance ...

The specified module could not be located in the ngx-toastr library

I'm having trouble finding the solution... ERROR in ./node_modules/ngx-toastr/fesm5/ngx-toastr.js Module not detected: Error: Unable to locate '/Users/vasanthan/Mean projects/node_modules/@angular/animations' in '/Users/vasanthan/Mean ...

Sending an external file using only the URL (https://.....) - here's how!

i need help with the following: .post("/getAttachments", (req, res, next) => { repository.getAttachments(req.body) .then((attachment) => { return res.sendFile('https://host.com' + attachment.req.path); ...

Reactivate IntelliJ IDEA's notification for running npm install even if you have previously selected "do not show again" option

One of the great features in Intellij IDEA is that it prompts you with a notification when the package.json has been changed, asking if it should run npm install, or whichever package manager you use. I have enjoyed using this feature for many years. Howe ...

Encountering issues with resolving dependencies in webdriverIO

I'm attempting to execute my WebdriverIo Specs using (npm run test-local) and encountering an error even though I have all the necessary dependencies listed in my package.json as shown below: [0-2] Error: Failed to create a session. Error forwardin ...

Having trouble with installing the npm package "testmybot"

I am attempting to utilize this sample to showcase the testing of a chatbot using the node "testmybot" package. However, when I run the "npm install" command, I encounter an error. Please refer to the attached screenshot for details. Steps I have taken ...

What is the best way to export an SVG node to a file using Node.js?

I've integrated d3 into my project with the help of a convenient package called https://www.npmjs.com/package/d3-node Using d3-node, I generated an svg file and here's the code snippet. const D3Node = require('d3-node') var d3n = new ...

When running `npm start:dev` in NestJs, I want to avoid triggering a rebuild every time I make a change in

Launching npm run start:dev within NestJs triggers the following sequence of events: 10:00:00 AM - Initiating compilation in watch mode... 10:00:10 AM - No errors found. Now monitoring for file modifications. Debugger now listening on ws://127.0.0.1:9229 ...

Struggling to generate a cookie through an express middleware

I'm currently working on setting up a cookie for new user registrations in my app to track their first login attempt. I came across this thread which provided some guidance but I'm still facing issues. Below is the snippet of my code: // Middle ...

What are the methods for capturing sequential API markings?

Currently, I am in the process of developing an API server that allows users to define their own routes. However, I have encountered a problem when trying to dynamically handle user-defined routes that match specific tokens. I have attempted two different ...

Challenges with utilizing Node.js on zsh

Recently, I made the switch from the bash shell to zsh while running Ubuntu via WSL. Initially, Node.js was installed and up to date on bash. However, when I tried npm install on a project in zsh, I realized that Node wasn't installed for zsh. Despite ...

Creating a comprehensive response involves merging two JSON responses from asynchronous API calls in a nodejs function block. Follow these steps to combine two REST API

New to JavaScript and the async/await methodology. I am working with two separate REST APIs that return JSON data. My goal is to call both APIs, combine their responses, and create a final JSON file. However, I am facing issues with updating my final varia ...