Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda