Stop socket.io from reconnecting

You might want to handle the reconnection yourself.

// Disables the automatic reconnection
var socket = io.connect('http://server.com', {
    reconnection: false
});

// Reconnects on disconnection
socket.on('disconnect', function(){
    socket.connect(callback);
});

Note: old versions used reconnect instead of reconnection.


I think what you need is to configure socket.io client to not reconnect is set property reconnect to false

I created a little server(server.js) to test this:

var io = require('socket.io').listen(8888);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Then I created this test.js to test that it does not reconnect

var client = require('socket.io-client'),
    socket = client.connect('http://localhost:8888', {
        'reconnect': false
    });

socket.on('connect', function () {
    socket.on('news', function (data) {
        console.log(data);
        socket.emit('my other event', { my: 'data' });
    });
});

For test.js to work you will need to install socket.io-client from npm issuing npm install socket.io-client or by adding socket.io-client (dev-)dependency to your package.json.

When I stop server.js while test.js is running test.js will return immediately which I believe is your desired result. When I set reconnect to true the client will try to reconnect to server which is not the desired behaviour

Tags:

Socket.Io