Networking – How Do Sockets Work Over Wireless Connections

networkingsockets

I've only worked on client side(specifically, mobile) applications using Android, where all networking is handled at the HTTP layer using framework provided components like HttpUrlConnection.

But push messaging systems like Websockets/XMPP etc, all maintain a persistent connection to the server. Even Google's GCM, which is baked into Google Play supported devices, maintain a persistent connection to the servers.

My question is, how does this work without draining battery? If we make continuous HTTP requests sequentially, the battery drain is significant. How are these persistent connections maintained without encountering the same problem?

Best Answer

An open TCP connection is a logical state. It does not imply that that data is always being sent back and forth. After the initial three-way handshake you've entered into the "connected" state. You're in that state until either a 3-way disconnect occurs or a keep-alive fails.

During the lifetime of the connection, resources from the underlying "physical" medium may be established to do transfers of data for that connection. In the case of a wired connection, this is a matter of transferring ethernet frames around. In the case of a 3G/4G wireless connection, this is done by establishing connections with the lower-level protocols as needed.

So for the life of the connection, there's no physical underlying data connection that exists. Instead it lies dormant waiting for either peer in the TCP connection to need to send data.

Another issue is that TCP is ack based. TCP peers can pretty efficiently keep each other apprised of what has been definitely recieved. Upon failure, TCP will retransmit. This works great for fairly reliable physical links, but tends to fall apart in very noisy/broken links, like your wireless connections. As you can imagine, acks/retransmissions would occur very frequently in these environments.

So typically, the underlying wireless protocol does everything it can to reduce the need for TCP retransmissions. For example, there's lots of error checking built into the wireless layer. Peers in the wireless realm (the base station/phone) also use a nak based protocol to tell the other side when they didn't receive something. Being nak based reduces the overhead in checking for errors (we assume everything fine unless the other side says its not). It also helps address errors before they bubble up to the TCP layer -- thus avoiding lots of TCP thrashing trying to retransmit. Moreover, it reduces the scope of any retransmissions to the wireless peers -- the phone doesn't need to ask the server somewhere on the Internet for the packet again, just the base station over the wireless link.

Related Topic