Skip to content

intermittent unexpected socket closure on Mac OS X #2610

@Trott

Description

@Trott

Ref: #1100
Ref: nodejs/node-v0.x-archive#16805

The following code will throw on OS X. It might take a while but it will happen. I usually see the error before runcount hits 2000.

'use strict';
const fork = require('child_process').fork;
const net = require('net');
const count = 12;
const port = 12346;

if (process.argv[2] === 'child') {
  let sockets = [];

  process.on('message', function(m, socket) {
    function sendClosed(id) {
      process.send({ id: id, status: 'closed'});
    };

    if (m.cmd === 'new') {
      sockets.push(socket);
    }

    if (m.cmd === 'close') {
      if (sockets[m.id].destroyed) {
        throw new Error('socket already destroyed');
      }
      sockets[m.id].once('close', sendClosed.bind(null, m.id));
      sockets[m.id].destroy();
    }

    if (m.cmd === 'clear') {
      sockets = [];
    }
  });

} else {
  const child = fork(process.argv[1], ['child']);

  const server = net.createServer();
  let sockets = [];

  server.on('connection', function(socket) {
    child.send({ cmd: 'new' }, socket);
    sockets.push(socket);

    if (sockets.length === count) {
      closeSockets(0);
    }
  });

  function createSockets() {
    let j = count, client;
    while (j--) {
      client = net.connect(port, '127.0.0.1');
    }
  }

  server.on('listening', function() {
    createSockets();
  });

  let runCount = 0;
  function closeSockets(i) {
    if (i === count) {
      console.log('run count: ' + ++runCount);
      child.send({ cmd: 'clear' });
      sockets = [];
      return createSockets();
    }

    child.once('message', function(m) {
      server.getConnections(function(err, num) {
        closeSockets(i + 1);
      });
    });
    child.send({ id: i, cmd: 'close' });
  };

  server.listen(port, '127.0.0.1');
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugIssues with confirmed bugs.macosIssues and PRs related to the macOS platform / OSX.netIssues and PRs related to the net subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions