Flutter run websocket on background?

2020-04-16 03:10发布

问题:

I already write a websocket based app, but when I back to home (both iOS and Android) the websocket are just not working anymore. How to make websocket still work on background? So that the service can always runing. Here is my stream and subscription:

channel = new IOWebSocketChannel.connect(wsUrl);
      globalChannel = channel;
      print("web socket channel connected.");

      // add channel.stream to streamController
      setState(() {
        _streamController = StreamController.broadcast();
        _streamController.addStream(channel.stream);
        globalStreamController = _streamController;
      });

      // Here we listen to ws stream and add to global messages
      // when enter chat page, globalSubscription should be stop
      // if globalSub were canceled, how to reopen it??
      globalSubscription = globalStreamController.stream.listen((data) {
}

How to let this streamcontroller still runing rather than limited in current page class?

回答1:

Other answers around SO and the web suggest that you can't just keep sockets open in the background (which seems reasonable, you'd be keeping open network connections that may affect battery life). Depending on your use case, you might be better looking at Push Notifications or something that checks on a schedule.

  • How to keep iphone ios xmpp connection alive while in the background?
  • Websocket paused when android app goes to background
  • https://www.quora.com/How-do-I-keep-Socket-IO-running-in-the-background-on-iOS


标签: dart flutter