Jonas Laux
Jonas Laux

Reputation: 449

Sails socket won't reconnect

I have two backends communicating to each other via sockets. On the sending one i only blast out. On the receiving one

const socketIOClient = require('socket.io-client');
const sailsIOClient = require('sails.io.js');
const io = sailsIOClient(socketIOClient);
io.sails.url = "http://route.to.my.backend";
io.sails.initialConnectionHeaders = {secret: process.env.SOCKETSECRET};

when the socket connection breaks, the sockets won't reconnect. I tried it with:

 io.sails.forceNew = true;

but it doesn't work. How can i force them to reconnect?

Upvotes: 2

Views: 1365

Answers (2)

Arthur Moisés
Arthur Moisés

Reputation: 11

Using the @ContinuousLoad solution I managed to get rid of the non connection problems. I also set another variable:

io.socket._raw.io._reconnectionAttempts = Infinity;

That way I can attempt to reconnect forever.

But I don't know why it works that way. I've been studying the sails.io.js code, https://github.com/balderdashy/sails.io.js/blob/master/dist/sails.io.js and the socket-io.client, especially the part of the manager: https://github.com/socketio/socket.io-client/blob/master/docs/API.md#new-managerurl-options

It seems that we really need to change the "reconnectionAttempts" and "reconnection" properties, and they must be changed while the socket isn't connected, as stated in the sails.io.js code:

// Set up connection options so that they can only be changed when socket is disconnected. var _opts = {};

But I really don't know why we must create private object properties. Not tested without the "_" part, though. Apparently, this is the only part of the internet that has an answer to this problem, so I'm glad that you figured it out, @ContinuousLoad! Thanks a lot!

Upvotes: 1

ContinuousLoad
ContinuousLoad

Reputation: 4922

This is an old question, but since I have a solution that seems to be undocumented (and no other answers were provided), I am posting for future reference.

Problem: my SailsSocket instance does not attempt reconnection while using the sails.io.js node module

Solution: manually set io.socket._raw.io._reconnection to true

Specifically, when your socket disconnects, set the above property to true and the socket will automatically attempt reconnection.

io.socket.on('disconnect', function() {
    io.socket._raw.io._reconnection = true;
});

It is rather ugly, because you must access the underlying socket.io socket client with ._raw, get the socket's manager with .io, and set another [pseudo-] private variable, ._reconnection, to true.

It should be emphasized that this whole "not reconncting" issue is only present using sails.io.js in node, while the browser implementation works fine.

Tested on: sails 0.11.0, sails.io.js node SDK 1.1.12, node 6.11.2

Upvotes: 7

Related Questions