Socket.io - Close Server

前端 未结 3 1777
广开言路
广开言路 2021-01-02 01:53

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.<

相关标签:
3条回答
  • 2021-01-02 02:39

    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?

    0 讨论(0)
  • 2021-01-02 02:42

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

    io.close()
    
    0 讨论(0)
  • 2021-01-02 02:51

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

    io.httpServer.close();
    
    0 讨论(0)
提交回复
热议问题