Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
How to get connection data in websocket client with ws library

Websocket client is running a script below:

let WebSocket = require('ws');
let readline = require('readline');

let url = 'wss://***.execute-api.us-east-1.amazonaws.com/test';
let ws = new WebSocket(url);

ws.on('open',  () => {
  console.log('...client.on.open: connected')
});

ws.on('message', data => {
  console.log(`...client.on.message: received from server: ${data}`)
});

ws.on('close', () => {
  console.log('...client.on.close: disconnected');
  process.exit();
});



readline.createInterface({
  input: process.stdin,
  output: process.stdout,
}).on('line', data => {
  console.log(`...client.sending to server: ${data}`)
  ws.send(data);
});

Is there an unique websocket's connection id that could be queried from within ws.on('open') function?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The connection is maintained by the object itself. If you wish to refer to it by an identifier and run multiple connections, you can store it in an object and assign your own ID as the key.

If you want to know which WebSocket connection is invoking an event, you can contain that information in a closure with the event when registering the handler.

EDIT:

let connections = {};
let nextId = 1;

function trackConnection(ws){
  const id = nextId;
  connections[id] = ws;
  nextId++;
  
  return id;
}

function openWebSocketConnection() {
  let ws = new WebSocket(url);
  
  const id = trackConnection(ws);

  ws.on('open',  () => {
    console.log('...client.on.open: connected on connection id: ' + id);
  });

  ws.on('message', data => {
    console.log(`...client.on.message: received from server on connection id: ${id}: ${data}`);
  });

  ws.on('close', () => {
    console.log('...client.on.close: disconnected on connection id: ' + id);
    process.exit();
  });
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!