c - IPC : Node JS server communication with simple C code

标签 c node.js server ipc

我有一个 C 代码,它在无限循环内等待输入并产生输出。

#include<stdio.h>
void flush() {
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

int main() {
    /*
     *  Load many files here
     */
    double d = 0;
    char input[1024];
    while (1) {
        d = d + 0.1;
        scanf("%[^\n]", input);        
        printf("%lf\n",d);
        fflush(stdout);
        flush();

    }
}

我需要另一个 Node JS 服务来监听某个端口并将输出作为响应发送。 我写了这段代码

var http = require('http');


var spawn = require('child_process').spawn;

var child = spawn('./dummyNLU.out');
child.stdin.setEncoding('utf-8');
child.stdin.cork();
var buffer = new Buffer(100);
var app = http.createServer(function(req,res){
    var string = buffer.write("HelloWorld!"); //this is for testing purpose
    child.stdin.write(buffer);
    child.stdin.end();
    child.stdout.on('data', function(data) {
        res.setHeader('Content-Type', 'text/plain');
        res.end(data);
    });
});

app.listen(3001);

我的这段代码似乎根本不起作用。

Node JS 服务器因错误而终止,Web 响应由 283 行响应组成,而不是 1 行。

谁能帮帮我吗?也欢迎其他一些解决问题的方法(从 C 可执行代码输出回复 Web 请求)。 预先感谢您。

最佳答案

child_process.spawn

将 C 代码二进制文件作为 Node 的子 Node 生成(双向通信)

var spawn = require('child_process').spawn
var child = spawn('main.exe')   
child.stdin.end('7')
child.stdout.on('data', (data) => { console.log(data); })
child.on('close', (code) => console.log('Exit code: ' + code))

如果它同时接收多个请求,这可能会很棘手,您将需要跟踪客户端(原始请求)以做出正确的响应(回答正确的请求客户端)

或者创建一个队列并为每个请求生成一个子级(一次最多有X个同时工作的子级),这样它们就会根据请求生成并在不需要时被杀死(让队列是限制事件 C 进程的总数)

PoC Node 生成子命令 (ls) 并打印结果(生成进程的 stdout)

    const spawn = require('child_process').spawn 
    const C = spawn('ls');let r='' 
    C.stdout.on('data',d=>r+=d) 
    C.on('close', () => console.log(r)); 

streaming-worker

designed to give you a simple interface for sending and receiving events/messages from a long running asynchronous C++ Node.js Addon.

<强> Streaming data from C to Node.js

关于c - IPC : Node JS server communication with simple C code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45914128/

相关文章:

node.js - 使用 Nodemailer 通过 zimbra smtp 发送无需密码的电子邮件

javascript - 使用 JavaScript 调用 Node.js 后端函数的最有效方法是什么

java - 应用客户端服务器,累加器编号错误

c - C 结构中的信号量 (sem_t) 是否已填充以尊重对齐?

c - 倒数算法错误

javascript - XMLHttpRequest 无法加载 http ://localhost:3000/get

node.js - 如何在nodejs中响应openssl提示

c - 另一个进程是否接收到对 UDP 数据报的响应?

c - 使用 Malloc 通过 GMP 处理大量数据

java - Apache Velocity 宏生成 Base64 编码的字符串