const readline = require('readline'); const WebSocket = require('ws'); // Configure readline for user input const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); /** * Prompt the user for the WebSocket server host. * @param {string} question - The question to display. * @returns {Promise} - The user input. */ function askQuestion(question) { return new Promise((resolve) => { rl.question(question, resolve); }); } /** * Connect to the WebSocket server and handle communication. * @param {string} host - The WebSocket server host. */ async function connectToWebSocket(host) { const ws = new WebSocket(`ws://${host}:64999`); ws.on('open', () => { console.log('Connected to the WebSocket server.'); showMenu(ws); }); ws.on('message', (data) => { console.log('Server response:', data.toString()); }); ws.on('error', (err) => { console.error('WebSocket error:', err.message); rl.close(); }); ws.on('close', () => { console.log('Connection closed.'); rl.close(); }); } /** * Display a menu of actions for the user. * @param {WebSocket} ws - The WebSocket connection. */ function showMenu(ws) { console.log(` Available commands: 1. prevconf - Get the previous configuration. 2. currconf - Get the current configuration. 3. Update - Send a new configuration. 4. Exit - Close the client. `); rl.question('Enter your choice: ', async (choice) => { switch (choice.trim()) { case '1': ws.send(JSON.stringify({ command: 'prevconf' })); break; case '2': ws.send(JSON.stringify({ command: 'currconf' })); break; case '3': const newConfig = await askForNewConfig(); ws.send(JSON.stringify(newConfig)); break; case '4': console.log('Closing the client...'); ws.close(); rl.close(); return; default: console.log('Invalid choice.'); } showMenu(ws); // Show the menu again after the action }); } /** * Prompt the user for a new configuration. * @returns {Promise} - The new configuration object. */ async function askForNewConfig() { const numMappings = await askQuestion('How many mappings do you want to add? '); const mappings = []; for (let i = 0; i < parseInt(numMappings, 10); i++) { const host = await askQuestion(`Enter host for mapping ${i + 1}: `); const port = await askQuestion(`Enter port for mapping ${i + 1}: `); mappings.push({ host, port: parseInt(port, 10) }); } return { mappings }; } /** * Entry point for the client. */ (async function main() { const host = await askQuestion('Enter the WebSocket server host (e.g., localhost): '); connectToWebSocket(host); })();