I am struggling how to implement websockets
autoreconnect in flutter. I use web_socket_channel, however, the plugin just wraps dart.io WebSocket, hence any solution based on WebSocket
class will work for me as well.
I already figured out, how to catch the socket disconnection, see the code snippet below:
try {
_channel = IOWebSocketChannel.connect(
wsUrl,
);
///
/// Start listening to new notifications / messages
///
_channel.stream.listen(
_onMessageFromServer,
onDone: () {
debugPrint('ws channel closed');
},
onError: (error) {
debugPrint('ws error $error');
},
);
} catch (e) {
///
/// General error handling
/// TODO handle connection failure
///
debugPrint('Connection exception $e');
}
I was thinking to call IOWebSocketChannel.connect
from within onDone
, however, this leads to a kind of infinite loop - since I have to close the _channel
prior calling connect
again, this on its turn calls onDone
again and so on.
Any help would be greatly appreciated!