1'use strict'; 2 3const common = require('../common'); 4const assert = require('assert'); 5const cluster = require('cluster'); 6const net = require('net'); 7 8let serverClosed = false; 9 10if (cluster.isWorker) { 11 const server = net.createServer(function(socket) { 12 // Wait for any data, then close connection 13 socket.write('.'); 14 socket.on('data', () => {}); 15 }).listen(0, common.localhostIPv4); 16 17 server.once('close', function() { 18 serverClosed = true; 19 }); 20 21 // Although not typical, the worker process can exit before the disconnect 22 // event fires. Use this to keep the process open until the event has fired. 23 const keepOpen = setInterval(() => {}, 9999); 24 25 // Check worker events and properties 26 process.once('disconnect', function() { 27 // Disconnect should occur after socket close 28 assert(serverClosed); 29 clearInterval(keepOpen); 30 }); 31} else if (cluster.isPrimary) { 32 // start worker 33 const worker = cluster.fork(); 34 35 // Disconnect worker when it is ready 36 worker.once('listening', function(address) { 37 const socket = net.createConnection(address.port, common.localhostIPv4); 38 39 socket.on('connect', function() { 40 socket.on('data', function() { 41 console.log('got data from client'); 42 // Socket definitely connected to worker if we got data 43 worker.disconnect(); 44 socket.end(); 45 }); 46 }); 47 }); 48} 49