Lesson · Networking
java.net Basics: Socket, ServerSocket and the options that matter
15 min readjava.net Basics
The first blocking call you write against a socket will hang until something ends it, and by default nothing does. java.net hands you the primitives: InetAddress lookups that block, a Socket with timeouts you must set, a ServerSocket with an accept loop, and DatagramSocket when boundaries matter more than guarantees.
InetAddress: the address object, and its blocking lookup
InetAddress.getByName("example.org") resolves a name and returns an address; getAllByName returns every address the name maps to, in the order the resolver reported them. Both consult the JVM's DNS cache first (the networkaddress.cache.ttl behaviour from the previous lesson), and when the name is not cached they perform network I/O with no timeout parameter of their own, so they block for as long as the resolver takes.
A returned object is either an Inet4Address or an Inet6Address, both immutable and safe to share. The surprise is getLocalHost(), which asks the OS for the local machine's name and typically resolves it right back: with a broken hostname entry or a misconfigured DNS suffix, that call blocks or throws, which is a strange failure for code that only wanted this machine.
If you need local addresses without the name round trip, NetworkInterface.getNetworkInterfaces() reads them from the OS without DNS, and InetAddress.getLoopbackAddress() returns the loopback address directly.
Every InetAddress lookup is a DNS query wearing a constructor's clothes. Cache the result when the address is stable, and treat the first call in a process as a call that can block.
Socket: connect, read, write, and the calls that end the wait
A client socket is created by connecting. new Socket(host, port) performs the connect in the constructor with no timeout you control, while new Socket() plus connect(new InetSocketAddress(host, port), timeoutMillis) puts a budget on the handshake. That budget covers connecting only: the socket it produces is still blocking, and by default every read on it can wait forever.
setSoTimeout(millis) is the read timeout, and it is the single most important line in production socket code. A read that exceeds it throws SocketTimeoutException, a subclass of InterruptedIOException; the connection stays open (a timeout ends that read, not the socket), so you can retry or give up deliberately. read() blocks until bytes arrive, and it returns -1 only at end of stream, never as an error.
Closing matters as much as reading. shutdownOutput() closes only your sending direction and sends FIN after the queued data ("I am done sending"), while the socket still reads replies. close(), usually through try-with-resources, releases the file descriptor; if another thread is blocked in a read at that moment, the read fails with SocketException rather than returning data or -1.
Set two timeouts and never skip them: the connect timeout and SO_TIMEOUT. Without them a stalled network turns into threads that wait forever, and nothing in your logs says why.
Socket options: the five that earn their place
Socket options are contracts and hints at the TCP layer, set through methods such as setTcpNoDelay, setSoTimeout, setKeepAlive and setReuseAddress. Most code needs five of them, and the rest is tuning you should not do without a measurement.
| Option | What it changes | When it matters |
|---|---|---|
TCP_NODELAY | Disables Nagle's algorithm, which delays small writes so they can be coalesced | Latency-sensitive protocols with small messages. It trades packet count for latency, so it is a choice, not a default win |
SO_TIMEOUT | How long a read waits before SocketTimeoutException (accept, on a ServerSocket) | Always, on both client and server sockets: without it a read waits forever |
SO_KEEPALIVE | The OS sends probes on an idle connection | Long-lived idle connections, and only eventually: the first probe is typically hours away with OS defaults, so it detects a dead path rather than proving liveness. Applications send their own heartbeats |
SO_REUSEADDR | Permits binding a port that still has connections in TIME_WAIT | Server restarts: without it, a quick restart can fail to bind with 'address already in use' |
SO_LINGER | What close() does with unsent data, including an immediate RST when set to zero | Almost never. Forcing resets to escape TIME_WAIT hides a protocol problem instead of fixing it |
Send and receive buffer sizes are tuning, not folklore: they change throughput on high-latency links and little else. Set them from a measurement or leave the OS defaults alone.
ServerSocket: bind, accept, hand off, repeat
new ServerSocket(9099, 50) binds the wildcard address, listens with a backlog of 50 and is ready for accept(). Each accept() blocks until a connection is complete, then returns a connected Socket; the loop hands that socket to a worker (a thread, an executor task or a virtual thread) and goes back to accepting.
Two rules keep the loop healthy. Never do real work on the accept thread, because every millisecond spent there is a connection waiting in the backlog queue. And expect accept() to end with SocketException when the server socket closes: that is the normal way a shutdown stops a listener, not a defect.
The accept loop is a dispenser, not a worker: accept, hand off, repeat. Whatever else happens between two accepts shows up directly as connection latency.
One socket conversation · :9099
The server binds port 9099 with a backlog of 50 and calls accept(). No client exists yet, so accept() blocks; the backlog is the kernel's queue for connections that complete before your code accepts them.
UDP: DatagramSocket keeps your boundaries, and nothing else
DatagramSocket plus DatagramPacket sends independent messages with no connection, no ordering and no retransmission. Each receive returns exactly one datagram, whole or not at all, which is the property TCP cannot offer.
Size is the first constraint: an IPv4 datagram can carry up to about 65,507 bytes of payload in theory, but anything above the path MTU is fragmented at the IP layer, and losing one fragment loses the whole datagram. Real protocols keep payloads small enough to avoid fragmentation entirely.
The second surprise is connect() on a DatagramSocket: it performs no handshake and establishes nothing. It only fixes a default peer so you can send(packet) without an address, and so datagrams from anyone else can be filtered. Everything UDP guarantees beyond the boundary is what your protocol layer adds back.
Choose UDP when a late datagram is worthless (discovery, metrics, real-time media) and TCP when the whole stream has to be correct. The datagram boundary is the one thing UDP gives you that TCP does not.
URL versus URI: the equals trap
URI compares syntactically: no network access, no surprises, safe for map keys and equality checks. URL.equals() and URL.hashCode() are documented as possibly performing DNS resolution to compare hosts, which puts blocking I/O inside a method named equals, on any thread, including one holding a lock. Two spellings that resolve to the same host may or may not compare equal, and the answer depends on the network moment.
The practical rule: parse and compare with URI, and use URL only where the old API forces it on you. URLConnection is that legacy HTTP surface (openConnection, setRequestProperty, getInputStream); the next lesson replaces it with java.net.http, and outside maintenance work you should not start new code on it.
Never use a URL as a HashMap key or in a hot-path comparison. URI is what you wanted in every one of those places.
A blocking call ends in exactly three ways
It returns data, it throws, or a timeout you set ends it. The defaults are effectively infinite (connect waits for the OS, SO_TIMEOUT 0 waits forever), so code that omits them converts every network stall into a thread that waits with no diagnosis. Set the connect timeout and SO_TIMEOUT on every socket, and treat read() == -1 as a normal end of stream rather than an error.
Interview angles
Connect timeout versus SO_TIMEOUT?+
The connect timeout bounds the handshake and lives on the connect call; SO_TIMEOUT bounds each read and lives on the socket. Both throw SocketTimeoutException, and if you skip them the wait ends only when the OS gives up or the peer finally answers.
A connect that gets no answer at all (no RST, no SYN-ACK) ends only when its budget expires, and a read ends only when SO_TIMEOUT fires or the peer sends something. Timeouts are therefore the only thing that converts silence into an exception you can log.
What does read() returning -1 mean?+
End of stream: the peer half-closed or closed its sending direction. It is a normal event, not an error, and with BufferedReader the same moment arrives as readLine() returning null.
A -1 arrives after everything already buffered has been consumed, so a protocol that reads until EOF still sees all the data. Distinguish it from SocketTimeoutException, which means nothing arrived in time and the socket remains open.
What is shutdownOutput() for?+
It half-closes the connection: TCP sends FIN after your queued data, the peer's read returns -1, and your side can still read the reply. Protocols whose messages are delimited by end of stream (some SMTP and HTTP/1.0 style conversations) depend on it.
Common misconception: That shutdownOutput() closes the socket. It closes one direction only; close() is what releases the descriptor, and a read blocked elsewhere then fails with SocketException.
Why is SO_KEEPALIVE not a substitute for application heartbeats?+
It is an OS-level probe with OS-level timing, and on common defaults the first probe is hours after the connection goes idle. It tells you a peer has stopped answering at the TCP layer, not that the application behind it is healthy.
Why is URL.equals() dangerous?+
It may perform DNS resolution to compare host names, so an equality check can block on the network and can return different results at different moments. URI compares the text, which is what identity checks and map keys need.
A URL used as a HashMap key in a hot path can trigger lookups under a lock, and two strings that name the same host ('localhost' and '127.0.0.1', or an uppercase host) may not compare equal. Parse with URI, compare what you parsed.
Follow-up: Where does that bite in practice?