Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda