【发布时间】:2021-11-23 11:19:53
【问题描述】:
按照net 和child_process 模块的官方节点文档,我归档了这个:一个生成子节点并通过net 模块连接的服务器。但是连接是断断续续的。代码是不言自明的,但我在代码 cmets 中添加了详细信息:
// 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 该怎么办了,已经尝试了我能做的一切......我做错了什么?
【问题讨论】:
标签: javascript node.js sockets ipc