Following the official node documentation of net
and child_process
modules, I archived this: a server that spawns a child and connect through net
module. But the connection is intermittent. The code is self explanatory, but I've add details in the code comments:
// 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
})
}
});
the expected log when execute node server
is:
server is listening
server listen callback
forked
child is ready
got socket connection
someone connected to server
child first message
but as the socket callback (at createServer
) is intermitent, we get this 50% of times:
server is listening
server listen callback
forked
child is ready
IDK what to do anymore, already tried everything I could... What am I doing wrong?
CodePudding user response:
Just found what was the problem... when I read the documentation I misunderstood that literally the net
server is being sent to the child process to share the "connections" to divide the processing in more than one process, and what I was trying to archive was just an 2 way communication with the forked child. I'll let this answer here if someone arrive at the same problem as me. This is the final code:
// 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');
})
}
});