TakahikoKawasaki / nv-websocket-client

High-quality WebSocket client implementation in Java.
Apache License 2.0
2.03k stars 293 forks source link

WebSocketState gets stuck in CONNECTING state #136

Open maxbaldrighi opened 6 years ago

maxbaldrighi commented 6 years ago

It's the first time I have to work with WebSocket and your library made the whole process very easy. So thank you!

But sometimes I face a very bad issue like I wrote in this issue title.

I have a very basic implementation of the WebSocketClient:

try {
    if (webSocket == null) {
    webSocket = new WebSocketFactory().createSocket(host, TIMEOUT);
    webSocket.addListener(mAdapter = new HLWebSocketAdapter(application));
    webSocket.addExtension(WebSocketExtension.PERMESSAGE_DEFLATE);
    webSocket.setPingInterval(Constants.TIME_UNIT_SECOND * 60);
    webSocket.connectAsynchronously();
     }
     else reconnect();          // which calls recreate()
 }
 catch (IOException | WebSocketException e) {
     e.printStackTrace();
     Log.e(LOG_TAG, e.getMessage());
 }

I have a ScheduledExecutorService (I'm developing an Android App) that checks every 5 seconds if WebSocket is correctly OPEN. If not I try to reopen the connection.

BUT, some times the connection never gets reopened and I continuously receive the callback onStateChanged() with state CHANGING.

Does anyone have an idea of what may cause the issue?

I'm experiencing it right now while I'm writing on both physical (LG connected with 4G) and virtual (using the PC connection) devices.

nicknabdullah commented 6 years ago

Hi @maxbaldrighi, I'm using this lib, but haven't used ScheduledExecutorService. If you please mention how you implemented "reopen the connection".

MadOne199 commented 6 years ago

Just a guess, but if you read the document under the code tab regarding reconnection, it says;Note that you should not trigger reconnection in onError() method because onError() may be called multiple times due to one error. Instead, onDisconnected() is the right place to trigger reconnection. Also note that the reason I use an expression of "to trigger reconnection" instead of "to call recreate().connect()" is that I myself won't do it synchronously in WebSocketListener callback methods but will just schedule reconnection or will just go to the top of a kind of application loop that repeats to establish a WebSocket connection until it succeeds.

The above sounds similar to your issue - it may trigger a thought that leads to a result? Are you allowing enough time to reconnect before checking the status again? Rather than checking the status, maybe just connect again when onDisconnected is triggered?

Just thoughts...