Socket.io - Close Server

2019-02-09 05:37发布

问题:

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.

回答1:

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?



回答2:

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

io.close()


回答3:

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

io.httpServer.close();