【发布时间】:2018-06-06 12:34:02
【问题描述】:
假设我有一个分叉子进程的父节点进程。我想在它们之间创建一个请求-响应机制,以便子级可以向父级发送消息(JSON)并等待响应,反之亦然。
我不想使用 HTTP,因为我希望机制尽可能紧凑和低延迟,而 HTTP 通常会有一些开销。此外,HTTP 是一个客户端-服务器协议,我想要一些双向的东西。 (我很高兴知道开销是否可以忽略,或者在这种情况下与使用管道、直接 TCP 套接字或 WebSocket 一样糟糕;这会让我的工作更轻松)。
我想要的最终结果是这样的。请注意,为了清楚起见,此代码使用 TypeScript,而不是因为答案也必须使用 TypeScript。
class Communicator {
// Callback for when a message is received by the Communicator
// Resolve returns a response to the sender, reject returns an error
onMessage : (data : any) => Promise<any>;
// Sends an object to the other process, and returns a promise
// that resolves with the response or rejects with the error reason
send(data : any) : Promise<any>;
}
在这种情况下,我将假设我们使用原生 process.send 机制,但如果像 WebSockets 这样的其他系统更好,那就有点不同了:
// PARENT
let cp = require("child_process").fork("./child.js");
let comm = new Communicator(cp);
await comm.send({property : 1});
.
// CHILD
let comm = new Communicator(process);
await comm.send({property : 1});
请求/响应系统应该支持成功类型和错误类型的响应,以及指示底层协议失败的错误无响应。
我应该如何在 Node 中实现它?如果我天真地尝试这样做,我会想到很多问题,因为多个请求和响应可以并行运行。有没有一个图书馆已经这样做了?我应该只使用 HTTP 吗?
【问题讨论】:
标签: javascript node.js asynchronous process ipc