gpt4 book ai didi

javascript - Node `net` 模块 IPC 服务器间歇性

转载 作者:行者123 更新时间:2023-12-04 13:24:22 33 4
gpt4 key购买 nike

遵循net的官方 Node 文档和 child_process模块,我存档了这个:一个服务器,它产生一个 child 并通过 net 连接模块。但是连接是断断续续的。代码是不言自明的,但我在代码注释中添加了详细信息:

// server.js
const childProcess = require('child_process').fork('child.js');
const server = require('net').createServer((socket) => {
console.log('got socket connection'); // this callback is intermitent
socket.on('data', (stream) => {
console.log(stream.toString());
})
});

server.on('connection', () => {
console.log('someone connected to server'); // this is running only if the code above runs (but its intermitent)
});

server.on('listening', () => {
console.log('server is listening'); // this is the first log to execute
childProcess.send('server', server); // send the server connection to forked child
});

server.listen(null, function () {
console.log('server listen callback'); // this is the second log to execute
});
// child.js
console.log('forked'); // this is the third log to execute
const net = require('net');

process.on('message', (m, server) => {
if (m === 'server') {
const socket = net.connect(server.address());
socket.on('ready', () => {
console.log('child is ready'); // this is the fourth log to execute
socket.write('child first message'); // this is always running
})
}
});
执行时的预期日志 node server是:
server is listening
server listen callback
forked
child is ready
got socket connection
someone connected to server
child first message
但是由于套接字回调(在 createServer 处)是间歇性的,我们有 50% 的机会得到这个:
server is listening
server listen callback
forked
child is ready
IDK该怎么办了,已经尝试了所有我能做的......我做错了什么?

最佳答案

刚刚发现问题出在哪里......当我阅读文档时,我误解了字面上的net服务器被发送到子进程以共享“连接”以将处理划分为多个进程,而我试图存档的只是与 fork 子进程的 2 路通信。如果有人遇到与我相同的问题,我会在这里回答这个问题。这是最终的代码:

// server.js
const childProcess = require('child_process').fork('child.js');
const server = require('net').createServer((socket) => {
console.log('got socket connection');
socket.on('data', (stream) => {
console.log(stream.toString());
})
});

server.on('connection', () => {
console.log('someone connected to server');
});

server.listen(null, function () {
childProcess.send(server.address());
});
// child.js
console.log('forked');
const net = require('net');

process.on('message', (message) => {
if (message.port) {
const socket = net.connect(message);
socket.on('ready', () => {
console.log('child is ready');
socket.write('child first message');
})
}
});

关于javascript - Node `net` 模块 IPC 服务器间歇性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69412154/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com