Stage 3: Core APIs, lesson 11 of 12

Networking: sockets, TCP and URLs

Intermediate3 min read@since 21Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

Java's java.net package covers low-level networking:

  • TCP (Socket, ServerSocket): a reliable, ordered connection. HTTP, databases and most protocols run on it.
  • UDP (DatagramSocket): fast, connectionless packets that may be lost or reordered. Used for DNS, streaming and games.
  • InetAddress looks up host names; URI parses and builds addresses safely.

A server binds to a port and accepts connections; each accepted connection is a Socket with an input and an output stream. With virtual threads, one thread per connection scales to thousands of clients.

For HTTP, use HttpClient (or Spring's clients) instead of raw sockets. Always set timeouts, or a slow or dead peer can block a thread forever.

Example

Java
// A tiny echo server: sends back every line it receives
try (var server = new ServerSocket(5000);
     var clients = Executors.newVirtualThreadPerTaskExecutor()) {
    while (true) {
        Socket socket = server.accept();
        clients.submit(() -> {
            try (socket;
                 var in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 var out = new PrintWriter(socket.getOutputStream(), true)) {
                socket.setSoTimeout(30_000);                 // don't wait forever
                String line;
                while ((line = in.readLine()) != null) out.println("echo: " + line);
            }
            return null;
        });
    }
}
The client
try (var socket = new Socket()) {
    socket.connect(new InetSocketAddress("localhost", 5000), 3_000);   // connect timeout
    socket.setSoTimeout(5_000);                                         // read timeout
    var out = new PrintWriter(socket.getOutputStream(), true);
    var in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out.println("hello");
    System.out.println(in.readLine());      // echo: hello
}

Common mistake

Forgetting timeouts. A socket without a read timeout can block a thread forever if the other side stops responding.

Under the hood

URL's equals and hashCode may do DNS lookups, so never use URL objects as map keys; use URI. Behind a proxy or load balancer, the socket's remote address is the proxy, not the user; read the forwarded headers your proxy sets. For production servers you'll usually use a framework (Netty, Spring WebFlux, Tomcat) rather than raw sockets, but knowing sockets explains what they do underneath.

Check yourself

Which protocol guarantees that data arrives in order?

How this connects

Where this leads

You've reached the end of this thread. Try a learning path for what's next.

Part of Job-ready backend developer.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.