Friday 28 April 2017

To try to reconnect contiously to the socket server from client side, if server hasn't started yet?

I am having a chat app using Socket.io and AngularJS 1.x. I have used https://github.com/btford/angular-socket-io for Socket. My factory/service is like below.

var serverBaseUrl = 'http://localhost:4000';
app.factory('socket', function (socketFactory) {
    try {
        var myIoSocket = io.connect(serverBaseUrl, {
            'reconnection delay': 1000,
            'reconnection limit': 1000,
            'force new connection': true
        });
        var socket = socketFactory({
            ioSocket: myIoSocket
        });
        return socket;
    } catch (e) {
        console.log('System : Socket server is out of service. We will look into this and bring it back up.');
        return null;
    }
});

I am able to reconnect to the server only for the case when Client Side Page is loaded and at that moment server is up and running, my factory has the socket value, if I stop the server and restart the server, the client is able to reconnect to the server. I have achieved this through by below-mentioned methods.

socket.on('reconnect', function () {
            console.log('System : Reconnected to the server');
            socket.emit("abc", xyz);
        });

socket.on('reconnecting', function () {
            console.log('System : Attempting to re-connect to the server');
        });

The above scenario is fine, but I am talking about the scenario when my app is loaded for the first time and at that moment my server is down or nodejs app service is stopped.. For this scenario, a factory is executed only once when an app is loaded on the browser. Let just say that after few minutes server was up and running, but the client will not be connected to the server unless user refreshed the page. But I don't want this, a client should be able to connect to the server without refresh. The client should continuously try to reconnect to the server, even if server/service is down.

How may I achieve this?



via shahakshay94

No comments:

Post a Comment