示例工程 08-ipc-invoke-handle
08-ipc-invoke-handle/demo-02-message-port/main/index.ts
import { app, MessageChannelMain } from "electron";
app.whenReady().then(() => {
const { port1, port2 } = new MessageChannelMain();
const received: number[] = [];
const acks: number[] = [];
let finished = false;
let timer: NodeJS.Timeout | null = null;
const finish = (): void => {
if (finished) return;
finished = true;
if (timer) clearTimeout(timer);
const ok =
received.length === 3 &&
acks.length === 3 &&
received.join(",") === "10,20,30" &&
acks.join(",") === "10,20,30";
process.stdout.write(
`${JSON.stringify({
evt: "smoke",
ok,
sent: 3,
received,
acks,
})}\n`,
);
port1.close();
port2.close();
app.quit();
};
port1.on("message", (event) => {
const value = (event.data as { value?: number }).value;
if (typeof value !== "number") return;
received.push(value);
port1.postMessage({ ack: value });
});
port1.start();
port2.on("message", (event) => {
const ack = (event.data as { ack?: number }).ack;
if (typeof ack !== "number") return;
acks.push(ack);
if (received.length === 3 && acks.length === 3) finish();
});
port2.start();
for (const value of [10, 20, 30]) {
port2.postMessage({ value });
}
timer = setTimeout(() => {
if (received.length < 3 || acks.length < 3) finish();
}, 2000);
});