13

I have a socket.io server in my app, listening on port 5759.

At some point in my code I need to shutdown the server SO IT IS NOT LISTENING ANYMORE.

How Can I accomplish this?

Socket.io is not listening on an http server.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Ari Porad
  • 2,834
  • 3
  • 33
  • 51

3 Answers3

16

You have a server :

var io = require('socket.io').listen(8000);
io.sockets.on('connection', function(socket) {
    socket.emit('socket_is_connected','You are connected!');
});

To stop recieving incoming connections

io.server.close();

NOTE: This will not close existing connections, which will wait for timeout before they are closed. To close them immediately , first make a list of connected sockets

var socketlist = [];
io.sockets.on('connection', function(socket) {
    socketlist.push(socket);
    socket.emit('socket_is_connected','You are connected!');
    socket.on('close', function () {
      console.log('socket closed');
      socketlist.splice(socketlist.indexOf(socket), 1);
    });
});

Then close all existing connections

socketlist.forEach(function(socket) {
  socket.destroy();
});

Logic picked up from here : How do I shutdown a Node.js http(s) server immediately?

Community
  • 1
  • 1
user568109
  • 47,225
  • 17
  • 99
  • 123
16

This api has changed again in socket.io v1.1.x it is now:

io.close()
Adedayo Omitayo
  • 206
  • 2
  • 3
3

The API has changed. To stop receiving incoming connections you should run:

io.httpServer.close();
josliber
  • 43,891
  • 12
  • 98
  • 133
Ilkka Oksanen
  • 87
  • 1
  • 3