farshad90
farshad90

Reputation: 31

Cordova: Keep socket.io connection alive

I'm currently developing an Apache Cordova app with Ionic Framework that should communicate through a WebSocket with my server and I use the Socket.Io library for it. Now there are two prolems I face:

  1. When the app goes into the background (cordova pause event), for example via the home or standby button, after a while, the socket gets closed & the client gets disconnected.

  2. When I exit the app via the hardware back button on android devices, the socket even gets closed immediately.

What I have tried so far:

Basically I just want to keep the WebSocket connection alive once the app was started by the user until it is killed manually via a task manager or similar.

I've thoroughly searched every related question on here but they didn't fit my case. I really need this thing to work and would appreciate any help.

Upvotes: 1

Views: 2957

Answers (2)

thanansan
thanansan

Reputation: 36

Once Websocket is closed, it will be destroyed. So that you can't make call back function to inform the websocket close event or can't connect from anywhere.

So that, I wrote reconnectSocket and call from another service.

call this reconnectSocket in a frequency from another class. (I'm calling for every 5 seconds interval). If the connection is closed, this will try to connect.

private subject: WebSocket;

 reconnectSocket() {
    console.log('reconnecting socket call');

    if (this.subject.readyState == 3) {// If webs-socket closed
      this.subject.close();

      let ws = new WebSocket(CHAT_URL);
      let self = this;
      ws.onmessage = function (event) {
        self.listener(event.data);
      };
      ws.onerror = this.onError;
      ws.onclose = this.onClose;
      ws.onopen = this.onOpen;
      this.subject = ws;
      console.log("websocket reconnected");
    }

Upvotes: 1

Kenneth Li
Kenneth Li

Reputation: 1742

You should use signalr instead of websocket and disable the hardware back button using JavaScript in your app. Then, the connection should be able to keep alive in your case 1 & 2.

Signalr can use Websocket as well, but actually you don't need to choose it since signalr will choose the best available protocol for you.

Upvotes: 0

Related Questions