Kano001 commited on
Commit
530bc68
1 Parent(s): dd8c371

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +23 -16
server.js CHANGED
@@ -1,5 +1,5 @@
1
  const WebSocket = require('ws');
2
- const { exec } = require('child_process');
3
 
4
  // Create a WebSocket server listening on port 7860
5
  const wss = new WebSocket.Server({ port: 7860 });
@@ -18,24 +18,31 @@ wss.on('connection', (ws) => {
18
  // Convert message (Buffer) to string
19
  const command = message.toString();
20
 
21
- // Execute the command with superuser privileges
22
- exec(command, (error, stdout, stderr) => {
23
- if (error) {
24
- ws.send(`Error: ${error.message}`);
25
- }
26
- if (stderr) {
27
- ws.send(`stderr: ${stderr}`);
28
- }
29
- if (stdout) {
30
- ws.send(`stdout: ${stdout}`);
31
- }
32
- }).stdout.on('data', (data) => {
33
- // Send the stdout data to the WebSocket client
34
  ws.send(`stdout: ${data}`);
35
- }).stderr.on('data', (data) => {
36
- // Send the stderr data to the WebSocket client
 
 
37
  ws.send(`stderr: ${data}`);
38
  });
 
 
 
 
 
 
 
 
 
 
39
  });
40
 
41
  // Event listener for client disconnects
 
1
  const WebSocket = require('ws');
2
+ const { spawn } = require('child_process');
3
 
4
  // Create a WebSocket server listening on port 7860
5
  const wss = new WebSocket.Server({ port: 7860 });
 
18
  // Convert message (Buffer) to string
19
  const command = message.toString();
20
 
21
+ // Split command into command and arguments
22
+ const [cmd, ...args] = command.split(' ');
23
+
24
+ // Spawn a child process to execute the command
25
+ const process = spawn(cmd, args, { shell: true });
26
+
27
+ // Send stdout data to the WebSocket client
28
+ process.stdout.on('data', (data) => {
 
 
 
 
 
29
  ws.send(`stdout: ${data}`);
30
+ });
31
+
32
+ // Send stderr data to the WebSocket client
33
+ process.stderr.on('data', (data) => {
34
  ws.send(`stderr: ${data}`);
35
  });
36
+
37
+ // Handle process completion
38
+ process.on('close', (code) => {
39
+ ws.send(`Process exited with code ${code}`);
40
+ });
41
+
42
+ // Handle errors
43
+ process.on('error', (err) => {
44
+ ws.send(`Error: ${err.message}`);
45
+ });
46
  });
47
 
48
  // Event listener for client disconnects