Skip to content
Java networking 6 min read

Networking Basics

Java has had first-class networking support baked right into the standard library since its earliest days — long before most languages treated the network as a built-in concern. The java.net package gives you everything from low-level TCP/UDP sockets to higher-level HTTP connections, all without any third-party dependencies.

Why Networking in Java?

Modern applications rarely run in isolation. They talk to databases over a network, call REST APIs, stream data, or accept connections from clients. Java’s networking APIs map directly to the fundamental building blocks of the internet:

  • IP addresses — how machines identify each other
  • Ports — how a single machine runs many network services at once
  • Sockets — the endpoints through which data flows between two programs
  • HTTP — the protocol your browser uses (and the one your code probably needs too)

Java’s java.net package wraps these concepts into clean, object-oriented classes so you can focus on your logic instead of low-level OS calls.

The java.net Package at a Glance

Class / InterfaceWhat it does
InetAddressResolves hostnames to IP addresses and vice versa
URLRepresents and parses a Uniform Resource Locator
URLConnectionOpens a generic connection to a URL resource
HttpURLConnectionExtends URLConnection with HTTP-specific controls
SocketClient-side TCP endpoint
ServerSocketServer-side TCP listener that accepts incoming connections
DatagramSocketUDP socket (connectionless, lower overhead)

Note: Java 11 introduced the java.net.http.HttpClient as the modern replacement for HttpURLConnection. Both are covered in the linked pages below, but HttpClient is the recommended choice for new projects.

How Network Communication Works

Every network conversation boils down to the same loop:

  1. A server opens a port and listens for incoming connections.
  2. A client looks up the server’s IP address and opens a socket to that port.
  3. Both sides exchange bytes over the established connection.
  4. Either side closes the connection when finished.

Java models step 1 with ServerSocket, steps 2–3 with Socket, and wraps the whole thing in familiar InputStream/OutputStream streams — the same streams you already know from Java I/O.

A Minimal Echo Server and Client

The simplest possible demonstration: a server that echoes whatever the client sends.

Server side:

import java.io.*;
import java.net.*;

public class EchoServer {
    public static void main(String[] args) throws IOException {
        // Listen on port 9000
        try (ServerSocket server = new ServerSocket(9000)) {
            System.out.println("Waiting for a client...");
            try (Socket client = server.accept();                      // blocks until connected
                 BufferedReader in  = new BufferedReader(
                     new InputStreamReader(client.getInputStream()));
                 PrintWriter   out  = new PrintWriter(
                     client.getOutputStream(), true)) {

                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println("Received: " + line);
                    out.println("Echo: " + line);   // send back
                }
            }
        }
    }
}

Client side:

import java.io.*;
import java.net.*;

public class EchoClient {
    public static void main(String[] args) throws IOException {
        try (Socket socket = new Socket("localhost", 9000);
             PrintWriter  out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(
                 new InputStreamReader(socket.getInputStream()))) {

            out.println("Hello, server!");
            System.out.println(in.readLine());
        }
    }
}

Output (client console):

Echo: Hello, server!

This tiny example already shows the full pattern you’ll use in real networked applications. Notice how try-with-resources automatically closes both the socket and the streams — always do this to avoid resource leaks.

TCP vs UDP

Java supports both major transport protocols:

FeatureTCP (Socket)UDP (DatagramSocket)
ConnectionConnection-oriented (handshake)Connectionless
ReliabilityGuaranteed delivery, orderedNo guarantee, no ordering
SpeedSlightly slowerFaster, lower overhead
Use caseHTTP, file transfer, chatDNS, video streaming, games

Most Java networking you’ll write uses TCP via Socket and ServerSocket. UDP is available through DatagramSocket and DatagramPacket when you need raw speed over reliability.

Under the Hood

When you call new Socket("example.com", 80), the JVM does several things behind the scenes:

  1. DNS resolution — the hostname is resolved to an IP address using the OS resolver (or InetAddress internally). The result is cached by the JVM for a configurable TTL (networkaddress.cache.ttl in java.security).
  2. TCP three-way handshake — the OS TCP stack sends a SYN packet, waits for SYN-ACK, and responds with ACK. This establishes the connection before your code sends a single byte.
  3. File descriptor allocation — the OS assigns a file descriptor to the socket. Every open socket counts against the process’s file descriptor limit (check with ulimit -n on Linux). This is why connection pooling matters at scale.
  4. Stream wrappingsocket.getInputStream() returns a raw InputStream backed by the OS kernel buffer. Wrapping it in a BufferedReader adds a userspace buffer, reducing expensive system calls.

Tip: Under high concurrency, consider Thread Pools & Executors or Virtual Threads (Java 21) to handle many simultaneous connections without spinning up one OS thread per client — the classic “thread-per-connection” model breaks down around 10,000 concurrent connections.

Ports: What You Need to Know

Ports are 16-bit numbers (0–65535) that let one machine run many network services simultaneously:

  • 0–1023 — “well-known” ports (HTTP = 80, HTTPS = 443, FTP = 21). Binding these requires root/admin privileges on most OSes.
  • 1024–49151 — registered ports for common applications.
  • 49152–65535 — dynamic/ephemeral ports that the OS assigns to outgoing connections automatically.

When you write a server for development, pick any port above 1024 (e.g., 8080, 9000) to avoid permission issues.

Exception Handling in Networking

Networking code throws checked exceptions you cannot ignore:

  • java.net.UnknownHostException — DNS lookup failed
  • java.net.ConnectException — connection refused (nothing listening on that port)
  • java.net.SocketTimeoutException — operation exceeded the timeout set via socket.setSoTimeout()
  • java.io.IOException — general I/O error on the stream

Always wrap networking code in proper try-catch blocks and set timeouts — a hung network call with no timeout will block your thread forever.

Socket socket = new Socket();
socket.connect(new InetSocketAddress("example.com", 80), 5000); // 5-second timeout
socket.setSoTimeout(3000); // 3-second read timeout

In This Section

  • Socket Programming — Build TCP client/server applications using Socket and ServerSocket, handle multiple clients, and understand the full socket lifecycle.
  • URL Class — Parse and work with URLs in Java, extract protocol/host/path/query components, and open connections directly from a URL object.
  • URLConnection — Use the abstract URLConnection class to read content from any URL resource, set request headers, and handle responses.
  • HttpURLConnection — Make HTTP GET and POST requests, inspect response codes, work with headers, and handle redirects using the built-in HttpURLConnection.
  • InetAddress — Resolve hostnames to IP addresses, look up the local machine’s address, and work with both IPv4 and IPv6 using the InetAddress class.
  • Socket Programming — dive deeper into building real client/server applications with full lifecycle management
  • Java I/O — networking streams build directly on the same InputStream/OutputStream model used throughout Java I/O
  • Multithreading — handle multiple simultaneous network clients by combining sockets with threads
  • Virtual Threads — Java 21’s lightweight threads make thread-per-connection servers practical at massive scale
  • Thread Pool — use ExecutorService to bound the number of threads serving network clients
  • Serialization — send Java objects across a socket connection by serializing them to a byte stream
Last updated June 13, 2026
Was this helpful?