Skip to content
Master Computer Network Interviews: 7 Core Modules, 20+ Diagrams, Java-Practical Deep Dive
Fundamentals 53 min read

Master Computer Network Interviews: 7 Core Modules, 20+ Diagrams, Java-Practical Deep Dive

This comprehensive guide covers seven core computer network modules — OSI/TCP-IP models, TCP handshakes, flow/congestion control, TCP vs UDP, HTTP evolution to HTTP/3 and QUIC, HTTPS encryption, and WebSocket — with 20+ diagrams, state machines, Java code examples, and interview-focused explanations for top tech companies.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

OSI Seven-Layer vs TCP/IP Four-Layer Models

The article opens by contrasting the OSI reference model (theoretical "ideal") with the TCP/IP model (industrial "living fossil"). A mapping diagram shows how OSI's seven layers collapse into TCP/IP's four: Application (merging OSI's Application, Presentation, Session), Transport, Internet, and Network Interface (merging Data Link and Physical). A mnemonic "应表会传网链物" (Application-Presentation-Session-Transport-Network-DataLink-Physical) aids memorization.

Layer-by-Layer Breakdown

1. Application Layer — Programmer's Direct Battlefield

OSI splits this into three layers; TCP/IP merges them. Java's HttpURLConnection, RestTemplate, and Nginx reverse proxy operate here. Common protocols: HTTP, HTTPS, DNS, FTP. Presentation-layer duties like SSL/TLS encryption and encoding are handled in Java by javax.net.ssl and serialization mechanisms — a concrete example of OSI theory mapping to practice.

2. Transport Layer — Foundation of End-to-End Reliability

OSI and TCP/IP agree here. TCP provides reliable transport (three-way handshake, four-way teardown, sliding window); UDP is fire-and-forget. Java's Socket / ServerSocket wrap TCP; DatagramSocket wraps UDP. Interview candidates must recite: TCP is connection-oriented, byte-stream; UDP is message-oriented, connectionless — the basis for Netty optimizations.

3. Network Layer (Internet Layer) — Addressing & Routing

Core protocol is IP. Routers forward by IP address; ARP maps IP to MAC; ICMP powers ping. Java's InetAddress encapsulates this layer.

4. Data Link & Physical Layers — Hardware Territory

TCP/IP combines them into Network Interface Layer. MAC addresses, switch forwarding, twisted pair, fiber belong here. Java developers rarely touch them directly, but ifconfig 's ether field reveals the MAC address during troubleshooting.

Core Comparison

Layer 7 (OSI Application) → TCP/IP Application : Protocols HTTP, FTP, DNS, SMTP; Data unit: Message

Layer 6 (OSI Presentation) → TCP/IP Application : Protocols SSL/TLS, JPEG, ASCII; Data unit: Message

Layer 5 (OSI Session) → TCP/IP Application : Protocols RPC, NetBIOS; Data unit: Message

Layer 4 (OSI Transport) → TCP/IP Transport : Protocols TCP, UDP; Data unit: Segment (TCP) / Datagram (UDP)

Layer 3 (OSI Network) → TCP/IP Internet : Protocols IP, ICMP, ARP; Data unit: Packet

Layer 2 (OSI Data Link) → TCP/IP Network Interface : Protocols Ethernet, PPP; Data unit: Frame

Layer 1 (OSI Physical) → TCP/IP Network Interface : No protocol, hardware standards; Data unit: Bit

Interview Key Points

Essential difference : OSI is a theoretical model; TCP/IP is the actual implementation the internet runs on.

Layering philosophy : Core is decoupling — each layer owns its responsibility, easing development and maintenance.

Data transmission process : Sender encapsulates top-down; receiver decapsulates bottom-up.

Common pitfalls : TCP/UDP at Transport, IP at Internet, MAC at Data Link.

Java Development Mapping

Writing HTTP APIs → Application Layer

Socket programming → Transport Layer (TCP/UDP)

Firewall config → Network Layer (IP/port)

Troubleshooting → ping (ICMP), traceroute

Netty gateway developers must handle TCP stick-packet/unpack (Transport), define magic numbers and serialization for custom protocols (Presentation/Application) — direct code-level manifestations of layering.

One-Sentence Interview Summary

"OSI 7-layer is an academic standard separating Presentation and Session for teaching; TCP/IP 4-layer merges top three into Application and bottom two into Network Interface, matching real protocol stacks. In Java I touch HTTP and TCP most; understanding layering lets me quickly pinpoint whether an issue is code logic, network policy, or infrastructure."

TCP Three-Way Handshake & Four-Way Teardown

TCP is connection-oriented, reliable, full-duplex. Handshake establishes reliable connection; teardown closes gracefully. Explained via state machines and real network programming.

Three-Way Handshake: Establishing Reliable Connection

Core Purpose

Both sides confirm each other's send/receive capabilities and negotiate Initial Sequence Numbers (ISN).

Full Flow (with sequence diagrams)

Client sends SYN (seq=x) → Server knows client can send .

Server replies SYN+ACK (seq=y, ack=x+1) → Client knows server can receive and send .

Client sends ACK (ack=y+1) → Server knows client can receive .

ISN is randomized, not zero, to prevent sequence-number prediction attacks.

Soul-Searching: Why 3? Not 2 or 4?

Not 2 : Prevents stale connection requests from creating phantom connections. With 2, server would allocate resources after SYN+ACK even if client never receives it; expired SYN packets could trigger bogus connections.

Not 4 : Server's SYN and ACK can be piggybacked in one packet, so 3 suffices; 4 would be redundant.

Four-Way Teardown: Graceful Close

Core Purpose

TCP is full-duplex; each direction closes independently. Each side must close its send channel (receive channel stays open until peer also closes).

Full Flow (with sequence diagrams)

Active side sends FIN → "I'm done sending."

Passive side ACKs → "Received; let me finish sending my data."

Passive side sends FIN → "I'm done sending too."

Active side ACKs → "Received; you may close."

Soul-Searching: Why 4? Not 3?

Passive side may have unsent data when receiving FIN; it cannot immediately send its own FIN. It must ACK first, finish sending, then send FIN. These two steps cannot merge, hence 4.

High-Frequency Follow-Ups

1. Why TIME_WAIT lasts 2 MSL?

MSL (Maximum Segment Lifetime) ≈ 2 minutes.

Role 1: Guarantees final ACK reaches peer. If peer misses it, it retransmits FIN; active side in 2 MSL can re-ACK.

Role 2: Lets all packets from this connection expire in the network, preventing old packets from interfering with a new connection on the same tuple.

2. SYN Flood Attack & Defenses

Attacker spoofs IPs, sends SYN; server replies SYN+ACK and waits for ACK that never comes, exhausting resources. Defenses: shorten SYN timeout, SYN Cookies (encode state in ACK sequence number), firewall filtering.

Java Practical Mapping

Socket.connect()

triggers handshake → ESTABLISHED. Socket.close() sends first FIN → FIN_WAIT_1.

Server ServerSocket.accept() returns Socket; if app forgets close(), connection leaks in CLOSE_WAIT 🔴.

Excessive TIME_WAIT consumes ports; mitigate with SO_REUSEADDR or kernel tcp_tw_reuse.

TCP Flow Control vs Congestion Control

Both ensure reliable delivery but solve different problems: flow control matches end-to-end speed (prevent receiver overflow); congestion control protects global network (prevent router collapse).

Flow Control: Sliding Window Protocol

Core Principle

Receiver advertises receive window (rwnd) in ACK's Window field. Sender's effective window = min(cwnd, rwnd). ASCII diagram illustrates: sender window capped by receiver's remaining buffer (4096 bytes).

Key Details

Zero window : rwnd=0 pauses sender.

Persist timer : Prevents deadlock if zero-window ACK lost; sender probes every 500 ms with 1-byte packet.

Dynamic rwnd : Grows as app reads; shrinks if app lags.

Silly Window Syndrome : Receiver advertises tiny windows, sender transmits tiny segments. Fix: Clark's solution (advertise only when window ≥ MSS or ½ buffer) + Nagle algorithm (accumulate small writes until MSS or ACK received).

Congestion Control: Four Core Algorithms

Core Concepts

cwnd : Sender-maintained, dynamically adjusted by perceived congestion.

ssthresh : Threshold separating exponential (slow start) from linear (congestion avoidance) growth.

Algorithm Execution Flow

Slow Start : Triggered at connection start / timeout retransmit. Logic: cwnd=1; doubles per ACK. Goal: Rapidly probe available bandwidth.

Congestion Avoidance : Triggered when cwnd ≥ ssthresh. Logic: cwnd+1 per RTT (linear). Goal: Grow cautiously, avoid congestion.

Fast Retransmit : Triggered by 3 duplicate ACKs. Logic: Retransmit immediately, no timeout wait. Goal: Reduce retransmission latency.

Fast Recovery : Triggered after fast retransmit. Logic: ssthresh=cwnd/2; cwnd=ssthresh; enter congestion avoidance. Goal: Avoid throughput cliff from slow start.

Why fast recovery skips slow start: 3 dup ACKs mean network still delivers packets — only sporadic loss, not severe congestion. Timeout signals true congestion.

cwnd Trend Graph

Shows sawtooth: exponential rise, linear rise, sharp drop on loss, recovery plateau.

Flow vs Congestion Comparison

Problem : Flow Control → Receiver capacity; Congestion Control → Network path capacity.

Scope : Flow Control → End-to-end; Congestion Control → Global (all hosts + routers).

Key Variable : Flow Control → rwnd; Congestion Control → cwnd.

Mechanism : Flow Control → Sliding window + advertisement; Congestion Control → Slow start, avoidance, fast retransmit, fast recovery.

Goal : Flow Control → Don't drown receiver; Congestion Control → Don't clog the network.

"Flow control: don't burst the receiver; Congestion control: don't jam the road." 🚦

Modern Evolution: Reno → BBR

Reno is loss-driven; performs poorly on high-BDP links (China-US dedicated lines) because it reacts only after loss, by which time router queues are long (Bufferbloat), causing latency spikes. Google's BBR uses bandwidth+RTT dual signals, periodically probing max BW and min RTT, no longer relying on loss — ideal for high BDP networks.

Reno : Signal = Loss; Best for low latency, low bandwidth.

CUBIC : Signal = Loss, cubic function; Linux default; better high-speed than Reno.

BBR : Signal = Bandwidth + RTT; Best for high latency, high bandwidth, mild loss.

Interview Bonus Points

Fast recovery avoids slow start because 3 dup ACKs indicate mild loss, not collapse.

Production tuning: disable Nagle ( TCP_NODELAY) for small-packet latency-sensitive apps (gaming, IM); increase rwnd for high-BDP links; enable BBR over CUBIC.

Final sender window = min(rwnd, cwnd) — both constraints apply simultaneously.

TCP vs UDP: Differences & Use Cases

Core Comparison

Connection : TCP connection-oriented (3WHS/4WHS); UDP connectionless.

Reliability : TCP guaranteed (ACK, retransmit, seq, checksum, flow/congestion control); UDP best-effort, no guarantee.

Congestion Control : TCP yes (slow start, avoidance, fast retransmit/recovery); UDP none.

Transport Style : TCP byte stream (no boundaries → stick/packet); UDP datagram (preserves boundaries).

Header Overhead : TCP 20-60 bytes; UDP fixed 8 bytes.

Speed : TCP slower (connection + reliability overhead); UDP very fast (no overhead).

Real-time : TCP poor (retransmit causes jitter); UDP excellent (loss doesn't block subsequent data).

Flow Control : TCP yes (sliding window); UDP none.

Duplex : Both full-duplex.

Traits : TCP accurate, complete, reliable; UDP fast, lightweight, real-time.

Analogy

TCP ≈ phone call 📞: dial, wait for "hello", confirm each sentence, repeat if missed, keep order. UDP ≈ walkie-talkie / social post 💬: shout, don't care if heard, order may scramble, but zero friction, minimal latency.

Typical Scenarios

TCP (must be reliable)

File transfer: FTP, SFTP, HTTP/1.1, HTTP/2 📁

Email: SMTP, POP3, IMAP 📧

Remote login: SSH, Telnet 💻

Financial transactions: payments, orders 💰

UDP (low latency paramount)

Real-time audio/video: live streaming, video conf, voice 🎥

Gaming: MOBA, FPS 🎮

DNS queries 🔍

Broadcast/multicast: DHCP, NTP 📡

IoT: sensor reporting 🤖

Mnemonic: "Need accuracy → TCP; Need speed → UDP." If occasional loss acceptable but latency critical (live, gaming), UDP wins; if zero byte loss required (payments, files), TCP mandatory.

Java Ecosystem Manifestation

TCP king : Socket / ServerSocket, Netty NioSocketChannel. RPC (Dubbo, gRPC), HTTP calls, DB connection pools — all TCP for timeout-retransmit, ordered delivery guarantees.

UDP light cavalry : DatagramSocket / DatagramPacket, Netty NioDatagramChannel. Service discovery (multicast heartbeat), metrics reporting, log collection (loss-tolerant) — tiny overhead, no connection setup, high throughput.

Example: Order payment API uses HTTP/2 over TCP (no loss); microservice health-check multicast heartbeat uses UDP (lightweight, real-time).

Interview Bonus

Mention TCP congestion control hurts real-time media → motivated QUIC (HTTP/3) over UDP: 0-RTT handshake, multiplexing without head-of-line blocking — huge plus.

Must-Ask Follow-Up 1: How does TCP guarantee reliability?

Sequence numbers + ACKs (order & dedup), timeout retransmit (loss), checksum (corruption), sliding window (flow control), congestion control (network stability).

Must-Ask Follow-Up 2: Can UDP achieve reliability?

Yes, at application layer. HTTP/3's QUIC and RTP for media implement ACK/retransmit, sequencing, congestion control on top of UDP — marrying UDP's low latency with TCP-like reliability.

HTTP 1.0/1.1/2.0/3.0 Evolution & QUIC

Traces evolution from "usable" → "usable well" → "peak performance", fundamentally solving latency and connection efficiency . Four phases: 1.0 foundation, 1.1 patches, 2.0 transport redesign, 3.0 layer disruption.

Version Comparison

Released : HTTP/1.0 1996; HTTP/1.1 1999; HTTP/2 2015; HTTP/3 2022 (RFC 9114).

Transport : HTTP/1.0 TCP; HTTP/1.1 TCP; HTTP/2 TCP; HTTP/3 UDP (QUIC).

Connection Model : HTTP/1.0 short (1 req/conn); HTTP/1.1 Keep-Alive + pipelining; HTTP/2 single TCP conn multiplexing; HTTP/3 single QUIC conn, independent streams.

Head-of-Line Blocking : HTTP/1.0 none (but huge conn overhead); HTTP/1.1 app-layer HOL blocking; HTTP/2 TCP-layer HOL blocking; HTTP/3 fully solved.

Header Compression : HTTP/1.0 none; HTTP/1.1 none; HTTP/2 HPACK; HTTP/3 QPACK.

Protocol Format : HTTP/1.0 text; HTTP/1.1 text; HTTP/2 binary; HTTP/3 binary.

Built-in Security : HTTP/1.0 no (needs HTTPS); HTTP/1.1 no (needs HTTPS); HTTP/2 recommends HTTPS; HTTP/3 mandatory TLS 1.3.

Key New Capabilities : HTTP/1.0 basic req/resp; HTTP/1.1 Host header, caching, range; HTTP/2 server push, stream priority; HTTP/3 connection migration, 0-RTT.

Per-Version Deep Dive

1. HTTP/1.0 — Short Connections, No Host, Primitive Caching 🐢

Established request-response model, GET/POST/HEAD. Fatal flaws: new TCP connection per request (3WHS+4WHS overhead), no Host header (no virtual hosting), only Expires caching. Latency (RTT) amplified unacceptably.

2. HTTP/1.1 — Keep-Alive, Pipelining, HOL Persists 🚶

Defaults to long connections ( Connection: keep-alive), adds Host header (virtual hosts), robust caching ( Cache-Control, ETag, Last-Modified), range requests, chunked encoding. Legacy issues: pipelining forces serial responses (app-layer HOL), verbose headers (repeated Cookie/UA), no server push. Result: TCP connection explosion, latency remains high.

3. HTTP/2 — Binary Framing, Multiplexing, HPACK, Server Push 🚗

Based on Google SPDY. Separates HTTP semantics from transport: binary framing, multiplexing (single TCP conn, parallel streams), HPACK (static dict + Huffman, 70%+ header reduction), server push, stream priority. Fatal legacy: still over TCP → TCP-layer HOL blocking : one lost packet stalls all streams. Also TCP+TLS handshake ≥ 2-RTT. In weak nets, HTTP/2 can underperform HTTP/1.1's multi-connection approach.

4. HTTP/3 — QUIC, 0-RTT, No HOL, Connection Migration 🚀

Drops TCP, runs on QUIC. Advantages: per-stream independent congestion control (one stream's loss doesn't block others), 64-bit Connection ID survives IP/port changes (WiFi↔4G seamless), optional FEC for loss recovery, 0-RTT/1-RTT handshake (3× faster than TCP+TLS), mandatory TLS 1.3, pluggable congestion control. Caveat: 0-RTT vulnerable to replay; only for idempotent requests (GET/HEAD).

QUIC Core Highlights

Stream-level congestion control — independent windows.

Connection ID — mobility without reconnect.

Forward Error Correction — recover without retransmit.

0-RTT data — instant resume.

High-Frequency Interview Q&A

HTTP/1.1 vs HTTP/2 HOL difference : 1.1 = app-layer (serial responses); 2.0 = TCP-layer (single packet loss blocks all streams).

Why HTTP/3 uses UDP : TCP HOL is protocol flaw, unsolvable at app layer; TCP handshake latency high; no connection migration; UDP allows custom transport logic.

HTTP/3 adoption : Google, Facebook, ByteDance at scale; Chrome/Firefox/Safari support; CDNs offer HTTP/3 acceleration.

Summary

1.0→1.1: Connection reuse.

1.1→2.0: App-layer HOL + header bloat.

2.0→3.0: TCP's own defects → unleash transport performance.

HTTPS Encryption: Symmetric + Asymmetric + CA Certificates

HTTPS inserts TLS/SSL between HTTP and TCP, combining symmetric + asymmetric + CA certificates to defeat HTTP's three fatal flaws: eavesdropping, tampering, impersonation 🔐.

Analogy: Sending a Package

You ship a phone (data) to a friend. Risks: courier reads letter (privacy), friend receives swapped fake (integrity/auth). HTTPS solves both with three tools.

1️⃣ Symmetric Encryption — Fast Shared Lockbox

Like a box locked with a single key both parties know. Fast, efficient for bulk data. Problem: how to deliver the key safely? If mailed, courier copies it → useless.

2️⃣ Asymmetric Encryption — Public Lock That Needs No Delivery

Two keys: Public key (open lock 🔓, freely distributable) and Private key (sole key 🔑, server-guarded). Flow: server publishes public lock; client generates random symmetric key, locks it with public lock, sends; only server's private key unlocks, retrieving symmetric key. Subsequent traffic uses symmetric key — fast + secure.

3️⃣ Man-in-the-Middle — Fake Courier Depot

Attacker intercepts, substitutes own public lock. Client encrypts symmetric key with fake lock; attacker decrypts, tampers, re-encrypts with real server's public lock, forwards. Both parties unaware.

4️⃣ CA Certificate — Unforgeable Notary Stamp 📜

CA = Internet's police. Server submits public key + identity (domain, org) to CA. CA signs with its private key → digital signature. Bundle = CA certificate. Browsers/OSes ship with trusted CA root public keys. Verification: use root public key to validate signature → proves certificate untampered; match domain → prevents wrong-site substitution; extract server's true public key → trust chain complete.

Why Not Just One Encryption?

Symmetric only : Key distribution is the Achilles' heel.

Asymmetric only : Hundreds to thousands times slower 🐢 — impossible for bulk HTTP payloads.

Golden Combo

Asymmetric: only for symmetric key exchange (solves distribution).

Symmetric: encrypts all application data (solves performance).

CA certificate: prevents public key substitution (solves MITM).

Symmetric vs Asymmetric Comparison

Speed : Symmetric blazing 🚀; Asymmetric glacial 🐢.

Key Count : Symmetric 1 shared; Asymmetric pair (pub+priv).

Core Risk : Symmetric key intercepted in transit; Asymmetric public key replaced by MITM.

Use Case : Symmetric bulk data encryption; Asymmetric key exchange, digital signatures.

Algorithms : Symmetric AES, ChaCha20; Asymmetric RSA, ECC.

Full TLS 1.2 Handshake (Sequence Diagram)

Illustrates ClientHello, ServerHello, Certificate, ServerKeyExchange, ClientKeyExchange, ChangeCipherSpec, Finished — 2-RTT.

CA Certificate Role (Anti-MITM)

Certificate = server's official ID 🪪. Contains domain, public key, CA signature, validity. Client verifies signature with pre-installed CA root public key; checks domain match; then trusts embedded public key.

Interview Bonus

Industry moved to TLS 1.3: 2-RTT → 1-RTT, 0-RTT resumption, major perf gain.

ECC (elliptic curve) beats RSA: stronger, shorter keys, faster — now mainstream.

Certificate chain validation: server returns chain; client verifies up to root.

"HTTPS uses hybrid encryption. Asymmetric safely delivers a temporary symmetric key; all subsequent traffic uses that symmetric key — security + performance. To stop MITM forging the public key, server sends a CA-signed digital certificate. Client validates with built-in CA root public key, confirms legitimacy, extracts server public key, proceeds with key exchange. CA certificate provides identity authentication and anti-tampering."

WebSocket Principles & Applications

Covers motivation → core principles → technical comparison → Java implementations → scenarios → production pitfalls.

One-Liner

WebSocket = full-duplex protocol enabling mutual proactive messaging ; borrows HTTP for initial handshake, then upgrades to independent protocol, solving HTTP's half-duplex + high-latency pain.

Why WebSocket?

HTTP is half-duplex request-response; server cannot push. Early "real-time" hacks: polling/long-polling (repeated TCP setup/teardown, high overhead/latency), Comet (HTTP hack, connection limits, proxy issues). WebSocket (RFC 6455) standardizes true full-duplex real-time.

Core Mechanism

2.1 Handshake (Core Exam Point)

Reuses HTTP 80/443 via Upgrade header — no extra ports, traverses firewalls/proxies. Client sends GET with Upgrade: websocket, Connection: Upgrade, random Sec-WebSocket-Key (Base64), Sec-WebSocket-Version: 13. Server replies 101 Switching Protocols with Sec-WebSocket-Accept = Base64(SHA1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")). Purpose: prevent accidental connections, ensure genuine handshake. Sequence diagram shows upgrade. Post-handshake, TCP connection persists; data flows as WebSocket frames, no HTTP header overhead.

2.2 Frame Format 📦

Minimal 2-byte header (6 with masking). Fields: FIN (1 bit, last frame), RSV1-3 (3 bits, extensions), Opcode (4 bits: 0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong), MASK (1 bit, client→server must mask), Payload Len (7/7+16/7+64 bits), Masking-Key (0/4 bytes), Payload Data. Table details each field.

2.3 Core Features

Full-duplex simultaneous send/receive.

Tiny framing overhead (2-14 bytes vs HTTP's dozens/hundreds).

No same-origin restriction (server validates Origin header).

Binary + text support.

💓 Heartbeat: Ping/Pong Frames

Long connections fear "zombie" state. Built-in Ping (0x9) / Pong (0xA): server sends Ping; client must promptly Pong (can echo payload). Achieves: liveness detection, idle keep-alive against NAT/proxy timeouts.

Reconnection: in onclose implement exponential backoff (1s, 2s, 4s… capped) for rapid recovery after server restart.

WebSocket vs HTTP Comparison

Connection : HTTP/1.1 short / Keep-Alive; WebSocket persistent long-lived.

Mode : HTTP/1.1 half-duplex (req-resp); WebSocket full-duplex.

Header Overhead : HTTP/1.1 dozens-hundreds bytes/req; WebSocket min 2 bytes.

Push : HTTP/1.1 none (polling simulation); WebSocket native server push.

Ports : Both 80/443 (WebSocket reuses HTTP).

Scenarios : HTTP/1.1 static resources, APIs; WebSocket real-time, push.

High-frequency, bidirectional, low-latency → choose WebSocket.

Java Ecosystem Implementations

1. Tomcat/Jetty Native (Servlet 3.1+)

Simple scenarios. @ServerEndpoint("/ws/{userId}") with @OnOpen, @OnMessage, @OnClose, @OnError.

2. Spring Boot WebSocket (Most Common)

Easy integration, STOMP sub-protocol support. Dependency: spring-boot-starter-websocket. Core: @EnableWebSocketMessageBroker + @MessageMapping + @SendTo.

3. Netty WebSocket (High-Performance)

Million-connection scale, internet giants. Core handler: WebSocketServerProtocolHandler. Advantages: zero-copy, Reactor model, custom frame processing.

Typical Scenarios

IM: chat, support, danmaku.

Real-time data: stock quotes, live scores, monitoring dashboards.

Collaboration: online docs, whiteboards, pair programming.

Gaming: multiplayer, real-time battles.

IoT: device status upload, remote control.

Push notifications: stock, sports, order status.

Polling in these scenarios = latency & server load disaster.

Production Pitfalls & Optimizations

Heartbeat : Nginx/firewall kill idle conns → mandatory ping/pong.

Reconnection : Client exponential backoff prevents thundering herd.

Connection Limits : File descriptor ceiling → tune ulimit -n.

Stick/Unpack : Netty's WebSocketFrameDecoder auto-handles; raw impl manual.

Security : WSS (TLS), validate Origin, auth via JWT in handshake headers.

Message Backlog : Server-side queue for offline clients.

Engineering essentials: WSS, Origin check, handshake auth (cookie/URL token), robust heartbeat/reconnect/serialization (Protobuf/JSON)/ACK.

Summary

WebSocket = standard real-time solution. Core: HTTP handshake upgrades to full-duplex TCP. Java: Spring Boot for simplicity, Netty for scale. Production must nail heartbeat, reconnection, security auth .

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

NettyWebSocketTCP/IPfour-way handshakethree-way handshakeQUICHTTPSHTTP/3flow controlcongestion controlOSI modelJava interview
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.