Networking & Real-Time7 min

The Anatomy of WebSocket and TCP in Real-Time Mobile Apps

Low latency in live location, chat and notification systems: the TCP 3-way handshake, the WebSocket upgrade and mobile battery optimization.

AuthorŞakir Ortataş

The Anatomy of WebSocket and TCP in Real-Time Mobile Apps — Interactive System Model

Socket & Network

Explore the isometric model, or switch between tabs to discover different architectures.

In courier tracking apps, instant messaging and trading dashboards, HTTP polling (firing requests continuously) both burns server traffic and drains mobile device batteries fast. The foundation of real-time communication is a persistent TCP connection and the WebSocket protocol.

The TCP Handshake and the WebSocket Upgrade

The client and server first establish a reliable TCP session with the SYN, SYN-ACK, ACK steps. Then a standard HTTP GET request carrying the 'Connection: Upgrade' header converts the protocol to WebSocket. From that point, full-duplex data flows in both directions over a single open socket.

Connection Drops on Mobile Networks and Heartbeats

When a mobile device switches cell towers or enters a tunnel, the TCP socket can silently drop. With advanced ping/pong heartbeat packets and smart reconnection algorithms, interruptions are repaired without the user noticing.

Room-Based Broadcasting and Scaling

When managing thousands of active socket connections, instead of broadcasting messages to every user, deliver them only to the relevant recipients through Socket.io or Redis Pub/Sub rooms. This keeps server CPU consumption to a minimum.

The Anatomy of WebSocket and TCP in Real-Time Mobile Apps · Live Code BlockNetworking & Real-Time · TS 5.x
The Anatomy of WebSocket and TCP in Real-Time Mobile Apps · Live Code Block
60 FPS · TS 5.x · Running
1@WebSocketGateway({ cors: { origin: "*" }, namespace: "chat" })
2export class RealtimeChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
3 @WebSocketServer()
4 server: Server;
5
6 handleConnection(client: Socket) {
7 const userId = client.handshake.auth?.userId;
8 if (!userId) return client.disconnect(true);
9 client.join(`room:${userId}`);
10 }
11
12 @SubscribeMessage("sendMessage")
13 async handleMessage(@ConnectedSocket() client: Socket, @MessageBody() data: ChatMessageDto) {
14 this.server.to(`room:${data.recipientId}`).emit("newMessage", {
15 ...data,
16 id: randomUUID(),
17 timestamp: Date.now(),
18 });
19 }
20
21 handleDisconnect(client: Socket) {}
22}
Contact

Let's turn your technical vision into a working product

TypeScript · React Native · React · NestJS · Node.js