11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst common = require('../common');
41cb0ef41Sopenharmony_ciconst assert = require('assert');
51cb0ef41Sopenharmony_ciconst cluster = require('cluster');
61cb0ef41Sopenharmony_ciconst net = require('net');
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_cilet serverClosed = false;
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_ciif (cluster.isWorker) {
111cb0ef41Sopenharmony_ci  const server = net.createServer(function(socket) {
121cb0ef41Sopenharmony_ci    // Wait for any data, then close connection
131cb0ef41Sopenharmony_ci    socket.write('.');
141cb0ef41Sopenharmony_ci    socket.on('data', () => {});
151cb0ef41Sopenharmony_ci  }).listen(0, common.localhostIPv4);
161cb0ef41Sopenharmony_ci
171cb0ef41Sopenharmony_ci  server.once('close', function() {
181cb0ef41Sopenharmony_ci    serverClosed = true;
191cb0ef41Sopenharmony_ci  });
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_ci  // Although not typical, the worker process can exit before the disconnect
221cb0ef41Sopenharmony_ci  // event fires. Use this to keep the process open until the event has fired.
231cb0ef41Sopenharmony_ci  const keepOpen = setInterval(() => {}, 9999);
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_ci  // Check worker events and properties
261cb0ef41Sopenharmony_ci  process.once('disconnect', function() {
271cb0ef41Sopenharmony_ci    // Disconnect should occur after socket close
281cb0ef41Sopenharmony_ci    assert(serverClosed);
291cb0ef41Sopenharmony_ci    clearInterval(keepOpen);
301cb0ef41Sopenharmony_ci  });
311cb0ef41Sopenharmony_ci} else if (cluster.isPrimary) {
321cb0ef41Sopenharmony_ci  // start worker
331cb0ef41Sopenharmony_ci  const worker = cluster.fork();
341cb0ef41Sopenharmony_ci
351cb0ef41Sopenharmony_ci  // Disconnect worker when it is ready
361cb0ef41Sopenharmony_ci  worker.once('listening', function(address) {
371cb0ef41Sopenharmony_ci    const socket = net.createConnection(address.port, common.localhostIPv4);
381cb0ef41Sopenharmony_ci
391cb0ef41Sopenharmony_ci    socket.on('connect', function() {
401cb0ef41Sopenharmony_ci      socket.on('data', function() {
411cb0ef41Sopenharmony_ci        console.log('got data from client');
421cb0ef41Sopenharmony_ci        // Socket definitely connected to worker if we got data
431cb0ef41Sopenharmony_ci        worker.disconnect();
441cb0ef41Sopenharmony_ci        socket.end();
451cb0ef41Sopenharmony_ci      });
461cb0ef41Sopenharmony_ci    });
471cb0ef41Sopenharmony_ci  });
481cb0ef41Sopenharmony_ci}
49