First look at each application and trigger the http service through the net service;
const http = require('http');
const net = require('net');
let netServer = net.createServer();
let httpServer = http.createServer((req, res)=>{
res.end('ok');
})
netServer.listen(3000,function(){
console.log("222222");
//netServer.close();
})
netServer.on('connection',(socket)=>{
httpServer.emit('connection',socket);
})
To put it simply, it means to initialize two services, one net service and one http service. Use the net service to listen to the port. After the client connects, the connection event of the http service is triggered and the socket is passed to the http service;
There is a line in it Comment, if you turn off the comment, the service will be shut down;
But look at another application, which involves the sub-process module and the handle transfer between processes; look at the program;
Parent process file:
var cp = require('child_process');
var net = require('net');
var child1 = cp.fork('./c.js');
var child2 = cp.fork('./c.js');
var netServer = net.createServer();
netServer.listen(3000,function(){
child1.send('server', netServer);
child2.send('server', netServer);
console.log("222222");
netServer.close();
})
Subprocess file:
const http = require('http');
let httpServer = http.createServer((req, res)=>{
// res.writeHead(200,{'Content-Type':'text/plain' + '\n'});
res.end('ok');
})
process.on('message', function(m, tcp){
console.log(m);
tcp.on('connection', function(socket){
httpServer.emit('connection',socket);
})
})
You see there is also a line of comments in the parent process file, but after removing the comments here, the service can work normally. What is the reason?
The net service of the parent process has been closed, and it no longer listens to port 3000. I don’t understand.
Understand at the code level that the parent process has ended, but the child process has not ended, but how does the requested stream run? , or how this code runs, my thoughts are a bit confusing, node explains it in simple terms, and it is really hard to read
Googled it and found a similar question on stackoverflow
The key should be in this section handleConversion
When there is a handle parameter when sending, handleConversion[type] will be called
You can see that when type: "net.Server", what is sent is server._handle
and when receiving is Such
That is to say, the parent process sends server._handle
, and the child process uses this handle to rebuild a server
So in fact, the server in the child process is different from the one in the parent process. The server.close of the parent process is natural. Will not affect child processes
Questions on stackoverflow can be found here