我需要在服务器端为客户端运行“ C”程序。该程序可以是交互式的。
我正在使用Node.js child_process类。但是我在这里看到一个问题:由于我需要保持程序的交互性,因此客户端和node.js服务器之间会来回交换消息。
1.program说:输入x的值:
将消息发送给客户端并获得一些输入值
。2.当Nodejs服务器从客户端接收到输入时,它将执行child_process.stdin.write
但是问题是,直到我标记了流的结尾,程序才执行。为此可能有什么解决方法?
就像在用户可用时将值刷新到程序中一样。
更新 :
test1.c
#include
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();
说它不起作用,它将等待直到流关闭。我该如何解决?由于我希望客户保持持续的互动,因此我很难预测何时结束直播。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句