我需要在服务器端为客户端运行一个“C”程序。这个程序可以是交互式的。
我正在使用 Node.js child_process 类。但我在这里看到一个问题:由于我需要保持程序交互,因此客户端和 Node.js 服务器之间会来回交换消息。
1.程序说:输入x的值:
将此消息发送给客户端并获取一些值作为输入
2.当Nodejs服务器收到客户端的输入时,它会执行child_process.stdin.write
但问题是,在我标记流的末尾之前,程序不会执行。有什么办法可以解决这个问题?
就像当用户可用时将值刷新到程序中一样。
Update :
test1.c
#包括
int main() {
int x, y;
printf("Enter x : ");
fflush(stdout);
scanf("%d", &x);
printf("Enter y : ");
fflush(stdout);
scanf("%d", &y);
printf("Value entered y is %d\n", y);
printf("Value entered x is %d", x);
}
编译以上代码,生成可执行文件a.out
var spawn = require('child_process').spawn;
var count = 0;
var exec = spawn('./a.out');
exec.on('error', function (err){
console.log("Error" + err );
});
exec.stdout.on('data', function(data){
console.log("in stdout.on.data : " + data.toString());
if (count == 0) {
exec.stdin.write('44\n');
count++;
}
else if (count == 1) {
exec.stdin.write('54');
count++;
}
if (count == 2) {
exec.stdin.end();
}
});
exec.stderr.on('data', function(data) {
console.log("in stderr.on.data : " + data);
});
exec.on('close', function (code) {
if (code != 0) {
console.log("Program ended with a error code : " + code);
}
});
在上面的node.js代码中如果我评论exec.stdin.end();
它不起作用,它会等到流关闭。我该如何解决这个问题?由于我希望客户能够持续互动,因此我很难预测何时结束直播。