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.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With