Skip to content

Race condition prevents Node.js process from exiting #935

Closed
@jamesshore

Description

@jamesshore

When using socket.io-client in Node, if the server is closed too soon after the client connects, disconnect() doesn't work properly and the process never exits.

To reproduce, use this code with Node v5.4.0 and socket.io-client@1.4.3:

(function() {
  "use strict";

  var clientIo = require("socket.io-client");
  var http = require("http");
  var io = require('socket.io');

  var httpServer;
  var server;

  var PORT = 5020;

  startServer(function() {
    console.log("SERVER STARTED");

    var client = clientIo("http://localhost:" + PORT);

    client.on('connect', function() {
      client.disconnect();
      stopServer(function() {
        console.log("COMPLETE! NODE SHOULD EXIT NOW.");
      });
    });
  });

  function startServer(callback) {
    httpServer = http.createServer();
    server = io(httpServer);
    httpServer.listen(PORT, callback);
  };

  function stopServer(callback) {
    httpServer.on("close", function() {
      console.log("SERVER CLOSED");
      callback();
    });

    server.close();
  };

}());

Output:

$ node spikes/socket.io/test.js 
SERVER STARTED
SERVER CLOSED
COMPLETE! NODE SHOULD EXIT NOW.
^C

If you introduce a delay in the stopServer() function, everything works fine:

  function stopServer(callback) {
    httpServer.on("close", function() {
      console.log("SERVER CLOSED");
      callback();
    });

    setTimeout(function() {
      server.close();
    }, 500);
  };

Output:

$ node spikes/socket.io/test.js 
SERVER STARTED
SERVER CLOSED
COMPLETE! NODE SHOULD EXIT NOW.
$

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions