行動網絡上的 WebSocket 為何顯示已連線卻收不到訊息,以及如何維持連線
The chat says "connected" and no messages arrive. Keeping WebSockets alive on mobile networks.
文章解釋,行動網絡上的 WebSocket 可能在連線指示仍顯示已連線時失效,令新訊息無法送達,並提出偵測及恢復連線的方法。建議以心跳偵測失效、按網絡變化重連,並採用帶隨機延遲的退避;應用程式進入背景時則關閉連線,返回前景後重新連線並補取訊息。伺服器可用遞增訊息 ID 讓用戶端補取漏訊,並以冪等處理避免重複;文中亦列出閒置逾時、切換網絡及伺服器重啟等測試。
The bug: the app shows a green "connected" dot, but new messages stop arriving. The user pulls to refresh, the missed messages appear, and live updates work again for a while. The server logs show the connection closed minutes ago, or never show it closing at all.
A WebSocket is one long-lived TCP connection. Phones are bad at keeping those, and they often don't tell the app when one dies. Here's why, and what a reliable client does about it.
Why the connection dies without anyone noticing
- NAT and carrier timeouts. Mobile networks put devices behind NAT gateways that drop idle TCP mappings, sometimes after only a few minutes without traffic. Neither end gets a close frame or a reset. The next message from the server just disappears.
- Network switches. When the phone moves from Wi-Fi to cellular, its IP address changes. The old TCP connection can't move with it. Until a write fails or a timeout fires, the client may still think it's connected.
- The app goes to the background. iOS suspends apps shortly after they leave the screen, and Android restricts background network access more with each release. A socket that belongs to a suspended app stops being read, and the server or a proxy closes it.
- Proxies and load balancers in between. Many have an idle timeout for WebSocket connections (often 60 seconds by default on some load balancers) and close connections that carry no frames for that long.
The common pattern: TCP only notices a dead peer when it tries to send. A client that only listens can sit on a dead connection for a very long time.
Heartbeats: detect the dead connection yourself
Send something regularly and expect something back.
-
OkHttp:
OkHttpClient.Builder().pingInterval(20, TimeUnit.SECONDS)sends WebSocket ping frames. If a pong doesn't arrive in time, OkHttp fails the socket and callsonFailure, which is where you reconnect. -
iOS:
URLSessionWebSocketTask.sendPing(pongReceiveHandler:)sends a ping and calls the handler when the pong arrives or with an error. It doesn't schedule itself, so run it on a timer and treat a missing pong as a dead connection. -
Application-level heartbeat: if a proxy in the path handles ping frames itself, or you need the server to confirm the session is still valid, send a small app message (
{"type":"ping"}) and expect a reply.
Pick an interval shorter than the shortest idle timeout in the path (often 20 to 30 seconds is used), and weigh it against battery use. Pings also keep NAT mappings alive while the app is in the foreground.
Reconnect properly
- Back off with jitter. Retry after 1, 2, 4, 8 seconds and so on, up to a cap, with a random component. If the server restarts and every client reconnects at the same instant, the reconnect storm can take it down again.
-
Reconnect on network change. Watch for path changes (
NWPathMonitoron iOS,ConnectivityManager.NetworkCallbackon Android) and reconnect right away instead of waiting for a heartbeat to fail. - Close on background, reconnect on foreground. Don't fight the OS. When the app goes to the background, close the socket cleanly and rely on push notifications for anything urgent. When it comes back, reconnect and catch up.
- Show the real state. "Connecting…" after a failed heartbeat is better than a green dot on a dead socket.
Don't lose messages across reconnects
Reconnecting gives you a new connection, not the messages sent while the old one was dead. The server has to help:
- Give every message (or event) an increasing ID or sequence number.
- On reconnect, the client sends the last ID it processed, and the server sends everything after it, or the client fetches the gap over a normal HTTP endpoint.
- Make message handling idempotent on the client, because a message near the reconnect can arrive twice.
Without this, every reconnect is a chance to miss a message silently, which is exactly the bug users report.
Testing it
- Idle timeout: connect, then send nothing for longer than your proxy's or load balancer's idle timeout. With heartbeats on, the connection should survive. With them off, you should see it die, which proves the timeout exists.
- Network switch: connect on Wi-Fi, turn Wi-Fi off so the phone moves to cellular, and send a message from another client. The app should reconnect and show it, within roughly one heartbeat interval.
- Background: send the app to the background for a few minutes, send messages from another client, then reopen the app. It should reconnect and show every missed message, in order, without duplicates.
- Server restart: restart the WebSocket server with several clients connected and watch the reconnect timing. With jitter, the reconnects spread out instead of arriving at once.
- Bad network: run the same tests on a slow, lossy network profile. Watch the frames in a WebSocket-capable inspector or proxy to confirm the pings and pongs actually go over the wire.
This article was created with the help of AI.
來源:DEV Community · dev.to