r/FlutterDev • • 22d ago

Article Flutter app and a web client in the same live chat rooms (Go WebSocket backend, Supabase) - 50s demo

I built RealTalk: a Flutter app and a plain JS web client both connected to one Go WebSocket server. Send on the phone, it shows up in the browser right away. Typing indicators, online counts and "delete for everyone" sync both ways.(Its a beginner project ik)

Demo: https://youtu.be/QC4QKiZmXq4 Code: https://github.com/Nithinaug/RealTalk

The Flutter side is app/lib/services/websocket_service.dart. It retries each endpoint and falls back to a hosted server if the local one is down.

Question: how do you handle WebSocket reconnects when the app goes to the background and comes back? I'd like something better than a plain retry loop

6 Upvotes

2 comments sorted by

1

u/MobileXapps 22d ago

Treating resume as "the connection is dead" is the right call. The part that makes it feel solid: give every message a server id or sequence number, and on reconnect send the last one you have, so the server (or a plain Supabase query) returns what was missed while the app was in the background. Without that, the reconnect works but messages still disappear.

For the retry itself, exponential backoff with random jitter, capped around 30 seconds, reset after a successful connect. Also listen for connectivity changes so you reconnect immediately when the network comes back instead of waiting out the backoff. And give sends a client-generated id, otherwise a message sent right before the drop can appear twice after the retry.

1

u/Wise_Phone_4112 22d ago

The OS usually kills the socket while the app is in the background, so on resume it's safer to assume the connection is dead and reconnect right away instead of waiting for a ping to time out. AppLifecycleListener (or WidgetsBindingObserver) gives you the resumed event, and connectivity_plus covers network switches. The part that matters more than the retry loop is catching up: keep the last message id you saw and ask the server for everything after it on reconnect, so you never depend on the socket having stayed up.