示例工程 10-ipc-streams-and-files
10-ipc-streams-and-files/demo-01-port-backpressure/main/index.ts
import { app, MessageChannelMain } from "electron";
const TOTAL = 12;
const MAX_IN_FLIGHT = 3;
app.whenReady().then(async () => {
const { port1, port2 } = new MessageChannelMain();
let sent = 0;
let acked = 0;
let inFlight = 0;
let peakInFlight = 0;
let finished = false;
const finish = (): void => {
if (finished) return;
finished = true;
clearInterval(timer);
console.log(
JSON.stringify({
evt: "smoke",
ok: sent === TOTAL && acked === TOTAL && peakInFlight <= MAX_IN_FLIGHT,
total: TOTAL,
sent,
acked,
peakInFlight,
}),
);
port1.close();
port2.close();
app.quit();
};
const pump = (): void => {
while (sent < TOTAL && inFlight < MAX_IN_FLIGHT) {
sent += 1;
inFlight += 1;
peakInFlight = Math.max(peakInFlight, inFlight);
port2.postMessage({ type: "chunk", seq: sent });
}
if (sent === TOTAL && inFlight === 0) finish();
};
port1.on("message", (event) => {
const data = event.data as { type?: string; seq?: number };
if (data.type !== "chunk") return;
port1.postMessage({ type: "ack", seq: data.seq });
});
port2.on("message", (event) => {
const data = event.data as { type?: string };
if (data.type !== "ack") return;
acked += 1;
inFlight = Math.max(0, inFlight - 1);
pump();
});
port1.start();
port2.start();
const timer = setInterval(pump, 20);
pump();
setTimeout(() => {
if (!finished) finish();
}, 3000);
});