Sockets and protocol framing
What you will learn
A socket is a communication endpoint. TCP provides an ordered byte stream, not application-message boundaries; UDP delivers individual datagrams without guaranteeing arrival or order. A protocol defines what bytes mean and where messages end. Use explicit framing, bounded lengths and deadlines before reading from any peer.
- Distinguish TCP streams and UDP datagrams.
- Implement bounded length-prefixed UTF-8 messages.
- Explain nonblocking readiness and address resolution.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Use only the included loopback peers and finite known messages. Port 0 selects a test-owned port. Do not expose the fixtures publicly. The runner enforces a process deadline.
Round trip with length-prefixed text
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main { static final InetAddress LOOP = InetAddress.getLoopbackAddress(); static void writeFrame(DataOutputStream out, String text) throws IOException { byte[] bytes = text.getBytes(StandardCharsets.UTF_8); if (bytes.length > 64) throw new IOException("frame too large"); out.writeInt(bytes.length); out.write(bytes); out.flush(); } static String readFrame(DataInputStream in) throws IOException { int length = in.readInt(); if (length < 0 || length > 64) throw new IOException("invalid length"); byte[] bytes = new byte[length]; in.readFully(bytes); return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); } static void exchange(String value) throws Exception { try (ServerSocket server = new ServerSocket(0, 1, LOOP); var worker = Executors.newSingleThreadExecutor()) { server.setSoTimeout(3000); var response = worker.submit(() -> { try (Socket peer = server.accept()) { peer.setSoTimeout(3000); String received = readFrame(new DataInputStream(peer.getInputStream())); writeFrame(new DataOutputStream(peer.getOutputStream()), "OK:" + received); return received; } }); try (Socket client = new Socket(Proxy.NO_PROXY)) { client.connect(new InetSocketAddress(LOOP, server.getLocalPort()), 3000); client.setSoTimeout(3000); writeFrame(new DataOutputStream(client.getOutputStream()), value); System.out.println(readFrame(new DataInputStream(client.getInputStream()))); if (!response.get(3, TimeUnit.SECONDS).equals(value)) throw new AssertionError(); } } } public static void main(String[] args) throws Exception { exchange("A17"); }}Expected output:
OK:A17The server reads exactly one bounded frame and returns one response. Both sides close their sockets. A port is assigned dynamically, not guessed.
Addresses, names and endpoints
An IP address identifies a network interface or endpoint address, while a port selects a transport endpoint. DNS can map host names to multiple IPv4 or IPv6 addresses; lookups can fail or be cached. URI parsing does not perform DNS. InetAddress.getLoopbackAddress() supplies a loopback address without a public lookup. The operating system chooses an available port when binding port 0; read getLocalPort() and use only that local peer.
Framing and deadlines
DataOutputStream.writeInt sends a four-byte big-endian length. Read the length first, reject negative or oversized values, then use readFully for exactly that many bytes. A stream read may return fewer bytes than requested or reach EOF. Socket.connect(address, timeout) bounds connection establishment; setSoTimeout bounds individual blocking reads, not a whole conversation or a write. For untrusted traffic, also enforce a total deadline, byte and request budgets, and close on failure. The following tiny local fixtures exchange known data.
Datagrams and readiness
A datagram carries a payload and addressing information; use packet offset and actual length. A too-small receive buffer truncates a datagram. UDP applications must explicitly handle loss, reordering and duplication if those matter. A Selector watches registered nonblocking channels for readiness; readiness is not a guarantee of a complete message. Maintain per-channel buffers, remove processed selected keys and handle zero-byte operations and EOF. The pipe example isolates readiness without introducing another network peer.
Receive one local UDP datagram
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main {
public static void main(String[] args) throws Exception { InetAddress loop = InetAddress.getLoopbackAddress(); try (DatagramSocket receiver = new DatagramSocket(new InetSocketAddress(loop, 0)); DatagramSocket sender = new DatagramSocket(new InetSocketAddress(loop, 0))) { receiver.setSoTimeout(3000); byte[] payload = "stock:3".getBytes(StandardCharsets.UTF_8); sender.send(new DatagramPacket(payload, payload.length, loop, receiver.getLocalPort())); DatagramPacket packet = new DatagramPacket(new byte[64], 64); receiver.receive(packet); System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength(), StandardCharsets.UTF_8)); } }}Expected output:
stock:3The receiver decodes only the bytes in the actual datagram. Loopback delivery in this test does not prove reliability over a real network.
Observe nonblocking readiness
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main {
public static void main(String[] args) throws Exception { Pipe pipe = Pipe.open(); try (var source = pipe.source(); var sink = pipe.sink(); var selector = Selector.open()) { source.configureBlocking(false); source.register(selector, SelectionKey.OP_READ); sink.write(ByteBuffer.wrap(new byte[]{42})); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3); ByteBuffer result = ByteBuffer.allocate(1); while (result.position() == 0 && System.nanoTime() < deadline) { selector.select(100); var keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { var key = keys.next(); keys.remove(); if (key.isReadable()) source.read(result); } } if (result.position() != 1) throw new IOException("read deadline"); result.flip(); System.out.println(result.get()); } }}Expected output:
42One selected readable channel supplies a byte. A pipe models selector mechanics, not TCP framing or connection establishment.
Common mistakes
Do not equate one TCP read with one message, allocate an array using an unchecked peer length, assume UDP retries automatically, or bind to every network interface for a local lab. A per-read timeout does not cap total request duration.
Practice
Change the TCP exchange to send the UTF-8 value café and predict its reply. Keep the 64-byte cap and deadlines.
Expected output:
OK:caféCompare your answer with the manual practice criteria.
Official reading: Socket · DatagramSocket · InetAddress · Selector. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sockets and protocol framing — knowledge check
Original networking and HTTP questions.
What does TCP preserve?
Why validate a frame length first?
What is bounded by setSoTimeout?
Which UDP packet property determines received bytes?
What does selector readiness indicate?