笔记:Nodejs 实时向 C++ 编译的可执行文件给予输入和获取输出

背景

我和几个同学当时想要去做一个多人联机的平面小游戏,但需要渲染视野。然而我们不会,只好请教大佬,而大佬不会 Javascript,所以他给我们的是 C++ 编译后的可执行文件,这就产生了延时。


原始方案

我当时写的是每一次游戏循环都运行一次程序,开启进程后向 stdin 加入数据,再从 stdout 获取。

就像这样:

js 复制代码
const exec=require('child_process').exec;

function runCommand(command,stdin)
{
    return new Promise((res,rej)=>{
        let child=exec(command,(err,stdout,stderr)=>{
            err||stderr? rej([err,stderr]):res(stdout));
        });
        child.stdin.write(stdin);
        child.stdin.end();
    });
}

运行起来的时候确实是可以用了,但是一多人就会有卡顿。

测试的时候发现,这种写法每一次都需要开启一个进程,再把这个进程关掉,这样就造成了时间上非常大的浪费,直接占掉至少 20ms 。这对于 30帧 的游戏来说都是不可理喻的。


改进写法

后来,我就想能不能在服务器一开始的时候就开启一个进程,而后就一直开着,服务器关了它才关。于是我先联系大佬把他的程序加上 while(true),而后查阅了大量资料。

后来我们通过 ChatGPT 发现,在 C++ 程序输出的时候 手动把缓冲区清空 ,就可以在 stdout 中得到输出。于是我们写出了下面的代码:

js 复制代码
const spawn=require('child_process').spawn;

const childProcess=spawn('./modules/vision.exe',[],{stdio:['pipe','pipe','inherit']});
childProcess.stdout.setEncoding('utf8');

var nowOutput=``;

childProcess.stdout.on('data',(data)=>{
    nowOutput=data.toString();
});

process.stdin.on('end',()=>{
    childProcess.kill();
});

function runCommand(stdin)
{
    return new Promise((res,rej)=>{
        childProcess.stdin.write(stdin);
        res(nowOutput);
    });
}

最后延时问题得到解决。

相关推荐
灰色小旋风8 分钟前
力扣20有效的括号(C++)
c++·算法·leetcode·职场和发展
weiabc20 分钟前
今日C/C++学习笔记20260223
c语言·c++·学习
悲伤小伞35 分钟前
9-MySQL_索引
linux·数据库·c++·mysql·centos
m0_5698814739 分钟前
C++中的组合模式高级应用
开发语言·c++·算法
m0_7301151143 分钟前
高性能计算负载均衡
开发语言·c++·算法
Hello_Embed1 小时前
LVGL 入门(十五):接口优化
前端·笔记·stm32·单片机·嵌入式
灰色小旋风1 小时前
力扣19删除链表的倒数第N个结点(C++)
c++·算法·leetcode·链表
孞㐑¥1 小时前
算法—记忆化搜索
开发语言·c++·经验分享·笔记·算法
xushichao19891 小时前
代码覆盖率工具实战
开发语言·c++·算法
chushiyunen1 小时前
人工智能-语义校验deepEval笔记
人工智能·笔记