const WebSocket = require('ws'); const { spawn } = require('child_process'); // Create a WebSocket server listening on port 7860 const wss = new WebSocket.Server({ port: 7860 }); // Event listener for new connections wss.on('connection', (ws) => { console.log('New client connected'); // Send a message to the client when they connect ws.send('Welcome to the WebSocket server!'); // Event listener for messages from the client ws.on('message', (message) => { console.log(`Received message: ${message}`); // Convert message (Buffer) to string const command = message.toString(); // Split command into command and arguments const [cmd, ...args] = command.split(' '); // Spawn a child process to execute the command const process = spawn(cmd, args, { shell: true }); // Send stdout data to the WebSocket client process.stdout.on('data', (data) => { ws.send(`stdout: ${data}`); console.log(`Log: ${data}`); }); // Send stderr data to the WebSocket client process.stderr.on('data', (data) => { ws.send(`stderr: ${data}`); console.log(`Log: ${data}`); }); // Handle process completion process.on('close', (code) => { ws.send(`Process exited with code ${code}`); }); // Handle errors process.on('error', (err) => { ws.send(`Error: ${err.message}`); }); }); // Event listener for client disconnects ws.on('close', () => { console.log('Client disconnected'); }); }); console.log('WebSocket server is running on ws://localhost:7860');