以下是使用Node.js实现的简单网页,包含两个按钮A和B。当按下按钮A时,会在服务器上执行命令“iperf3 -s -p 11111”,当按下按钮B时,会停止这个进程。

const http = require('http');
const { exec } = require('child_process');

// 服务器监听的端口号
const port = 3000;

// 创建HTTP服务器
const server = http.createServer((req, res) => {
  // 设置响应头
  res.setHeader('Content-Type', 'text/html');
  
  // 根据请求路径返回不同的页面内容
  if (req.url === '/') {
    res.statusCode = 200;
    res.write('<html><body>');
    res.write('<button onclick="startProcess()">A</button>');
    res.write('<button onclick="stopProcess()">B</button>');
    res.write('<script>');
    res.write('function startProcess() {');
    res.write('  fetch("/start")');
    res.write('    .then(response => response.text())');
    res.write('    .then(data => console.log(data));');
    res.write('}');
    res.write('function stopProcess() {');
    res.write('  fetch("/stop")');
    res.write('    .then(response => response.text())');
    res.write('    .then(data => console.log(data));');
    res.write('}');
    res.write('</script>');
    res.write('</body></html>');
    res.end();
  } else if (req.url === '/start') {
    res.statusCode = 200;
    
    // 执行命令"iperf3 -s -p 11111"
    exec('iperf3 -s -p 11111', (error, stdout, stderr) => {
      if (error) {
        res.write('Error starting process');
        res.end();
      } else {
        res.write('Process started');
        res.end();
      }
    });
  } else if (req.url === '/stop') {
    res.statusCode = 200;
    
    // 停止进程
    exec('pkill iperf3', (error, stdout, stderr) => {
      if (error) {
        res.write('Error stopping process');
        res.end();
      } else {
        res.write('Process stopped');
        res.end();
      }
    });
  } else {
    res.statusCode = 404;
    res.end('Not found');
  }
});

// 启动服务器
server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

将以上代码保存为一个名为server.js的文件,然后在终端中使用以下命令运行服务器:

node server.js

服务器将在本地的3000端口上运行。在浏览器中打开http://localhost:3000/,即可看到包含两个按钮的页面。按下按钮A时,会在服务器上执行命令“iperf3 -s -p 11111”;按下按钮B时,会停止该进程

请实现一个网页页面有2个按钮A和B。按下按钮A的时候在服务器上执行一个命令iperf3 -s -p 11111当按下按钮B时停止这个进程。请使用nodejs完整的实现

原文地址: https://www.cveoy.top/t/topic/iRIn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录