socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

no way to shutdown a server cleanly

Open msmouse opened this issue 12 years ago • 29 comments

Hi, I'm seeking for a way to shutdown a server. The current behavior is, when I call close() on engine, clients disconnect, but connect again immediately. Even if I call socket.io.close() on disconnect, the server is still listening.

And, can I suppose if socket.io.close() is called,(and references from my program is all deleted), the socket will be subject to garbage collection?

"use strict"

var svr = require('socket.io')(12332); var clt1 = require('socket.io-client')('ws://127.0.0.1:12332'); var clt2 = require('socket.io-client')('ws://127.0.0.1:12332'); svr.on('connection', function(socket) { console.log("svr connected"); svr.engine.close(); });

clt1.on('connect', function() { console.log('clt connected'); }); clt1.on('disconnect', function() { console.log('clt disconnected'); // clt1.io.close(); }); clt1.on('error', function() { console.log('clt error'); });

msmouse avatar Jun 07 '14 21:06 msmouse

Hi quick question here @s-a do you experienced EARDDRESINUSE? or the port is still in use ? When use nodemon or others?

mandaputtra avatar Jul 18 '19 14:07 mandaputtra

This issue still exists.... Ctrl-C killing the server would still persist the socket connections, and upon refresh of client, it will ask for another new socket + reconnecting the old socket... the server is not disconnected from the first connection, another refresh will trigger an extra socket...

allenchuang avatar Sep 09 '19 22:09 allenchuang

https://github.com/socketio/socket.io/issues/1602#issuecomment-120561951

I am using the following with Set instead of an object (and delete):

const connections = new Set();

server.on("connection", connection => {
  connections.add(connection);
  connection.once("close", () => {
    connections.delete(connection);
  });
});

const shutdownHandler = once(() => {
  console.log("Shutting down");
  httpServer.close(err => {
    if (err) {
      console.error(err);
      process.exitCode = 1;
    }
  });

  for (const connection of connections) {
    connection.destroy();
  }
});

process.on("SIGINT", shutdownHandler);

n1ru4l avatar May 01 '20 20:05 n1ru4l

@n1ru4l does this work for you? I have done a similar solution but I get destroy is not a function. There is a disconnect property on the socket but calling that does not make the server shut down.

TheLudd avatar May 26 '20 15:05 TheLudd

@TheLudd https://github.com/dungeon-revealer/dungeon-revealer/blob/f5dcce720cee0e0d41e012cfb5c5bd5af3e77687/server/index.js#L50-L72

It works (for us).

n1ru4l avatar May 26 '20 15:05 n1ru4l

This might help.. added in socket v4 // make all Socket instances disconnect io.disconnectSockets();

https://socket.io/docs/v4/server-api/#server

mfahadshah avatar Jan 13 '23 19:01 mfahadshah

I still experience server hang-when-close with socket.io v4.7.4 . Cutting underlying TCP connection still work, calling server.disconnectSockets(true) did not.

This is a renewed snippet of the TCP connection trick, thanks for information in this thread.

import type net from 'node:net';
import type http from 'node:http';

/**
 * record alive TCP connections, to force disconnect them during shutdown
 * (socket.io may have problem close all connections.)
 * @return a function to close all TCP sockets
 */
export function prepareTcpConnect(server: http.Server): () => void {
  const sockets = new Set<net.Socket>();
  server.on('connection', conn => {
    sockets.add(conn);
    conn.on('close', () => {
      sockets.delete(conn);
    });
  });

  return () => sockets.forEach(s => s.destroy());
}

jokester avatar Feb 02 '24 14:02 jokester

@jokester I don't think this should be needed. Isn't io.close() sufficient?

https://github.com/socketio/socket.io/blob/e36062ca2df0b1a4adcf986bafc3fd92675d3896/lib/index.ts#L745-L760

It should close both:

  • the Engine.IO server (io.engine.close()): https://github.com/socketio/engine.io/blob/ff0fbfb61f2509ef302870cfd993344c1d035e7d/lib/server.ts#L389-L398
  • and the HTTP server: https://nodejs.org/api/http.html#serverclosecallback

Also, I was not able to reproduce the issue:

// server.js
import { createServer } from "node:http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {});

const port = process.env.PORT || 3000;

io.on("connection", (socket) => {
  console.log(`connect ${socket.id}`);

  socket.on("disconnect", (reason) => {
    console.log(`disconnect ${socket.id} due to ${reason}`);
  });
});

io.of("/chat").on("connection", (socket) => {
  console.log(`[chat] connect ${socket.id}`);

  socket.on("disconnect", (reason) => {
    console.log(`[chat] disconnect ${socket.id} due to ${reason}`);
  });
});

httpServer.listen(port, () => {
  console.log(`server listening at http://localhost:${port}`);
});

setTimeout(() => {
  io.close();
  console.log("PROCESS SHOULD NOW EXIT");
}, 10_000);
// client.js
import { io } from "socket.io-client";

const port = process.env.PORT || 3000;

const socket = io(`http://localhost:${port}`);

socket.on("connect", () => {
  console.log(`connect ${socket.id}`);
});

socket.on("connect_error", (err) => {
  console.log(`connect_error due to ${err.message}`);
});

socket.on("disconnect", (reason) => {
  console.log(`disconnect due to ${reason}`);
});

const socket2 = io(`http://localhost:${port}`, {
  forceNew: true
});

const socket3 = io(`http://localhost:${port}/chat`, {
  forceNew: true
});

const socket4 = io(`http://localhost:${port}`, {
  forceNew: true,
  transports: ["polling"]
});

const socket5 = io(`http://localhost:${port}`, {
  forceNew: true,
  transports: ["websocket"]
});

That being said, I only found one change impacting the close() method since the opening of the issue, so it might not be completely fixed...

darrachequesne avatar Feb 05 '24 08:02 darrachequesne

@darrachequesne sorry I don't have a good reproduction or insight in code.

When developing my app using socket.io I think my server stuck at 5% or 10% of all runs, until I cut the TCP sockets.

I'm currently reading socket.io code to write an experimental adapter, maybe I can be lucky enough to find a hint 🤔

jokester avatar Feb 19 '24 09:02 jokester