You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在所有rcon回调函数执行完成后执行代码?

解决RCON异步响应收集后再返回HTTP响应的问题

你的核心问题是RCON的response事件是异步触发的(UDP分块返回响应),而你当前在conn.connect()后立刻调用res.end(),导致HTTP响应提前结束,后续的RCON响应内容无法写入。同时process.exit()会直接终止Node进程,导致Express服务器崩溃,这也是错误的。

修改后的代码

const express = require('express');
var Rcon = require('rcon');

const app = express();
const port = 3000;
app.use(express.urlencoded({extended: true}));

app.get("/", function(req,res){
  res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
    let resp = "";
    const ip = req.body.serverip;
    const pass = req.body.pass;
    const command = req.body.command;

    const options = {
      tcp: false,
      challenge: true
    };

    const conn = new Rcon(ip, 27015, pass, options);

    conn.on('auth', function () {
      console.log("Authenticated");
      console.log("Sending command:" + command);
      conn.send(command);
    });

    // 收集所有RCON响应片段
    conn.on('response', function(str)  {
        console.log("Response: "+str);
        resp += str;
    });

    conn.on('error', function (err) {
      console.log("Error: " + err);
      // 发生错误时,返回错误信息并结束HTTP响应
      res.setHeader("Content-Type", "text/html; charset=UTF-8");
      res.end(`<!DOCTYPE html><html><body>请求出错:${err}</body></html>`);
      conn.end(); // 关闭RCON连接
    });

    conn.on('end', function () {
      console.log("Connection closed");
      // 所有响应收集完成,返回最终HTML
      res.setHeader("Content-Type", "text/html; charset=UTF-8");
      res.end(`<!DOCTYPE html><html><body>${resp}<br>Done</body></html>`);
    });

    conn.connect();
});

app.listen(port, function(){
  console.log("Server is listening on port " + port);
});

关键修改点说明

  1. 收集所有响应片段:用resp变量累加所有response事件返回的内容,而不是实时写入HTTP响应,确保不会遗漏分块的UDP数据。
  2. 延迟结束HTTP响应:将res.end()移到RCON连接的end事件中,确保只有在所有RCON响应接收完成、连接关闭后,才返回完整的HTTP响应。
  3. 移除process.exit():该命令会终止整个Node进程,导致Express服务器停止运行,完全不符合Web服务的需求。
  4. 错误处理优化:在error事件中主动返回错误信息并关闭RCON连接,避免客户端长时间等待响应。
  5. 变量声明优化:用const/let替代var,提升代码可读性和作用域安全性。

内容的提问来源于stack exchange,提问作者shiro_1941

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:45:32