PlugFox / ws

WS: A compact, highly efficient WebSocket library. Easily establish, manage, and reconnect WebSocket connections in real-time apps.
https://pub.dev/packages/ws
MIT License
39 stars 5 forks source link

Websocket no longer works after some time #11

Closed martinpelli closed 3 months ago

martinpelli commented 7 months ago

Describe the bug if you leave the app in background for hours, and the app is not killed by the OS, I mean when you enter it doesn't shows the splash screen, listener stops getting triggered.

      ..stream.listen((message) {

      })
      ..stateChanges.listen((state) {

      })

Both of them stop working after being in background for some long time.

Expected behavior When opening the app it should try to reconnect, unless app is killed by the OS

Desktop (please complete the following information):

Smartphone (please complete the following information):

PlugFox commented 7 months ago

That can be a dart:io problem. Try to add a ping capabilities. For example, send a ping message from BE every 5 minutes to the client. If you don't receive that message in the last 5 minutes, just reconnect it.

martinpelli commented 7 months ago

@PlugFox I tracked the error and I am constantly getting:

flutter: CONNECTING
flutter: CLOSING
flutter: CLOSED

I think the problem is that mi bearer token is expiring, when app is opened I refresh it, but I am not passing that token to headers again. I can't find a method to update options or headers without assigning a new object to WebSocketClient

final wsHeaders = {"Authorization": "Bearer $bearerToken"};

webSocket = WebSocketClient( WebSocketOptions.vm( headers: wsHeaders, //need a method to update this connectionRetryInterval: ( min: const Duration(milliseconds: 500), max: const Duration(minutes: 1),

I am trying to find a method to update headers, is there any?

PlugFox commented 7 months ago

I think no right now.

Try to pass mutable Map<String, String> and update that map by references

martinpelli commented 7 months ago

@PlugFox I removed the middleware and all seems to works fine, is not confirmed but almost confirmed that this problem is with bearer token. But I made wsHeader a global variable without final keyword, and I am updating the token and websocket keeps trying to reconnect so maybe in code's library you are creating a new object instead of passing it by reference?

And I am sure the token is okay because it's working with other endpoints

Also my server is returning 401 when token is expired, but I can't catch that error using below code, is not printing anything

 ..stream.listen((message) {

      }).onError((e){
          print(e);
        }
      ..stateChanges.listen((state) {

      }).onError((e){
           print(e);
      }