Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter websocket disconnect listening

In Flutter, I wanna listen to websocket disconnect event, how to achieve that? The websocket connect will be drop when app goes to background, I still not found a method to let it continuesly running in background (does anyone have solution?), So I have to detect if a websocket connect is lost or something, so that I can re-connect when lost connection. Pls help if anyone knows how to achieve that.

like image 289
Nicholas Jela Avatar asked Jun 03 '18 03:06

Nicholas Jela


People also ask

How do I close WebSocket connection in flutter?

close method Null safety Closes the WebSocket connection. Set the optional code and reason arguments to send close information to the remote peer. If they are omitted, the peer will see WebSocketStatus. noStatusReceived code with no reason.

How do I check my WebSocket connection status in flutter?

You can find out if websocket is closed by implementing onDone callback. See the example below: _channel = IOWebSocketChannel. connect( 'ws://yourserver.com:port', ); /// /// Start listening to new notifications / messages /// _channel.

Why does WebSocket disconnect?

WebSocket disconnects can happen by choice, or due to exceptional/error conditions. Here is some information about what happens in each case: Clean disconnect: During a clean disconnect, the user or application will initiate a disconnect sequence.


3 Answers

You can find out if websocket is closed by implementing onDone callback. See the example below:

      _channel = IOWebSocketChannel.connect(
        'ws://yourserver.com:port',
      );

      ///
      /// Start listening to new notifications / messages
      ///
      _channel.stream.listen(
        (dynamic message) {
          debugPrint('message $message');
        },
        onDone: () {
          debugPrint('ws channel closed');
        },
        onError: (error) {
          debugPrint('ws error $error');
        },
      );

Hope that helps.

like image 141
Angel Todorov Avatar answered Oct 13 '22 15:10

Angel Todorov


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
like image 23
Danny Tuppeny Avatar answered Oct 13 '22 17:10

Danny Tuppeny


If your server closes the connection just use pinginterval like this

ws.pingInterval = const Duration(seconds: 5);

onDone should be called.

basic ping pong is enough.

like image 2
Aklesh Singh Avatar answered Oct 13 '22 16:10

Aklesh Singh