Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io - Close Server

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.

like image 860
Ari Porad Avatar asked Apr 14 '13 14:04

Ari Porad


People also ask

How do I stop a Socket.IO server?

close([callback])​ Closes the socket.io server. The callback argument is optional and will be called when all connections are closed.

Does Socket.IO reconnect after disconnect?

Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.

How do I know if a Socket is disconnected io?

the dropCheck emits a ping and set a timmer of 4 seconds. the user handle the emited ping and responds with another ping. a: if the response comes within 4 secs the 4 secs timmer is cancelled and refreshes the 60 seconds timmer (restarting the process)

Is Socket.IO difficult?

As explained above, getting started with Socket.IO is relatively simple – all you need is a Node. js server to run it on. If you want to get started with a realtime app for a limited number of users, Socket.IO is a good option. Problems come when working at scale.


2 Answers

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?

like image 158
user568109 Avatar answered Sep 22 '22 10:09

user568109


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

io.close()
like image 39
Adedayo Omitayo Avatar answered Sep 20 '22 10:09

Adedayo Omitayo