Spaces:
Paused
Paused
Create server.js
Browse files
server.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const WebSocket = require('ws');
|
| 2 |
+
const { exec } = require('child_process');
|
| 3 |
+
|
| 4 |
+
// Create a WebSocket server listening on port 3000
|
| 5 |
+
const wss = new WebSocket.Server({ port: 3000 });
|
| 6 |
+
|
| 7 |
+
// Event listener for new connections
|
| 8 |
+
wss.on('connection', (ws) => {
|
| 9 |
+
console.log('connected');
|
| 10 |
+
|
| 11 |
+
// Send a message to the client when they connect
|
| 12 |
+
ws.send('WebSocket server!');
|
| 13 |
+
|
| 14 |
+
// Event listener for messages from the client
|
| 15 |
+
ws.on('message', (message) => {
|
| 16 |
+
console.log(`Received message: ${message}`);
|
| 17 |
+
|
| 18 |
+
// Convert message (Buffer) to string
|
| 19 |
+
const command = message.toString();
|
| 20 |
+
|
| 21 |
+
// Execute the command without sudo
|
| 22 |
+
exec(command, (error, stdout, stderr) => {
|
| 23 |
+
if (error) {
|
| 24 |
+
ws.send(`Error: ${error.message}`);
|
| 25 |
+
console.log(`Error: ${stderr}`);
|
| 26 |
+
return;
|
| 27 |
+
}
|
| 28 |
+
if (stderr) {
|
| 29 |
+
ws.send(`stderr: ${stderr}`);
|
| 30 |
+
console.log(`Process: ${stderr}`);
|
| 31 |
+
return;
|
| 32 |
+
}
|
| 33 |
+
if (stdout) {
|
| 34 |
+
ws.send(`stdout: ${stdout}`);
|
| 35 |
+
console.log(`Log: ${stdout}`);
|
| 36 |
+
return;
|
| 37 |
+
}
|
| 38 |
+
//ws.send(`stdout: ${stdout}`);
|
| 39 |
+
});
|
| 40 |
+
});
|
| 41 |
+
|
| 42 |
+
// Event listener for client disconnects
|
| 43 |
+
ws.on('close', () => {
|
| 44 |
+
console.log('Client disconnected');
|
| 45 |
+
});
|
| 46 |
+
});
|
| 47 |
+
|
| 48 |
+
console.log('WebSocket server is running on ws://localhost:3000');
|