根据官方node文档中net
和child_process
模块的指导,我实现了以下功能:一个通过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
我不知道该怎么办了,已经尝试了我所能做的一切......我错在哪里了?