简体   繁体   中英

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?

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();
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM