Reputation: 19379
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?
Upvotes: 0
Views: 2570
Reputation: 487
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();
});
}
Upvotes: 2