The original address: www.brandhuang.com/article/156…

In our app project for Cordova+ Vue, we have been plagued by websocket disconnection problems

An Android phone will drop calls in an uncountable number of phones when it is backed to the desktop or locked screen. When li enters the APP, it will find that the message cannot be received or received

IPhone drops calls as soon as it locks the screen…

Since websocket performs an “onclose” method when the server fails to connect or is disconnected, we have reconnected it.

However, in the process of using our app, if the screen is locked for a long time, messages still cannot be sent. Only after clearing the background of the app and re-entering or re-logging in to the app (websocket link will be created during login) can the message return to normal

Websocket. readyState has four states:

Value State Description
0 CONNECTING Socket has been created. The connection is not yet ope
1 OPEN The connection is open and ready to communicate.
2 CLOSING The connection is in the process of closing.
3 CLOSED The connection is closed or couldn’t be opened

Messages can be sent and received only when the state value is 1.

So I thought, can I detect the status value when I open the app or unlock the app? Reconnect when it’s not one, right?

The first thing that comes to mind is to use HTML5 API “VisibilityChange” to judge the visibility of a page. First, I tested it on the web, and it seemed to work. But when packaged as an app, it doesn’t work on ios? !!!!!!!!!

This scenario — failed

Looking through the documentation for Cordova, I found that there are several events officially provided, and the “pause” and “resume” events are the ones I want

For details, see the official document Cordova Events

When the mobile phone Home button returns to the desktop or locks the screen, the Pause event is triggered

When entering the mobile app or unlocking the phone, the app’s “Resume” event will be triggered

So we just need to listen to these two events in app. vue, and then determine the state of websocket to operate, the main code is as follows:

mounted(){
    let _that = this
    document.addEventListener("resume".function () {
        if(_that.ws.readyState ! = =1){
          _that.$store.dispatch('reloadWebSocket', getAgentId())
        }
      }, false);
}
Copy the code

This scheme has been used in our test app for several days. According to the feedback, we haven’t found the problem of not sending messages that often occurred before

I just learned to use Websocket for a short time. If there are other better solutions, I hope I can get your advice

Thank you for reading