Java TCP Sockets: ServerSocket and Socket

A TCP connection is a reliable, ordered stream of bytes between two programs. Java exposes it through ServerSocket, which accepts connections, and Socket, which reads and writes. The examples here run a server and its clients in the same program on the loopback address.

Share

Contents

How TCP connections work

TCP gives two programs a reliable, ordered, two-way stream of bytes over an unreliable network. A connection starts with a three-way handshake (SYN, SYN-ACK, ACK) between a client and a server that is listening on a port. After that, the operating system numbers every byte, retransmits lost segments, reorders late ones, and slows the sender down when the receiver's buffer fills up (flow control). Your program never sees packets: it writes bytes into a send buffer and reads bytes out of a receive buffer, and the kernel does the rest.

Java's classic socket API maps directly onto this. A ServerSocket listens and accept() returns one Socket per client; a client creates a Socket to the server's address and port. Each socket offers an InputStream and an OutputStream, whose calls block until data can be moved.

TCP APIs in the JDK
APISinceBest for
Socket, ServerSocketJava 1.0Simple blocking clients and servers
SocketChannel, SelectorJava 1.4 (NIO)Many connections on few threads; see NIO selectors
Reimplemented Socket on NIOJava 13 (JEP 353)Same API, simpler implementation, ready for virtual threads
Virtual threadsJava 21 (JEP 444)Blocking code that scales to many connections
SSLSocketJava 1.4 (JSSE)Encrypted TCP; see SSL sockets

All programs run a server and its clients in one process on the loopback interface, on JDK 21 under Linux.

An echo server and two clients

A server binds a ServerSocket to a port and calls accept(), which waits for a client and returns a Socket for that connection. The client creates a Socket to the same address and port. Each side then has an input stream and an output stream.

The server below upper-cases each line it receives. It handles every connection on its own virtual thread, so the code can block on reads without limiting how many clients are served. Two clients connect one after the other and send two lines each.

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

public class EchoServer {

    static final AtomicInteger connections = new AtomicInteger();

    // One virtual thread per connection: simple blocking code that still scales
    static void serve(ServerSocket server) {
        while (!server.isClosed()) {
            try {
                Socket s = server.accept();
                connections.incrementAndGet();
                Thread.ofVirtual().start(() -> handle(s));
            } catch (IOException e) {
                return;                                   // server socket closed
            }
        }
    }

    static void handle(Socket s) {
        try (s;
             BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(),
                     StandardCharsets.UTF_8));
             PrintWriter out = new PrintWriter(s.getOutputStream(), true,
                     StandardCharsets.UTF_8)) {
            String line;
            while ((line = in.readLine()) != null) {      // null: the client closed its side
                out.println(line.toUpperCase());
            }
        } catch (IOException e) {
            System.out.println("connection error: " + e);
        }
    }

    public static void main(String[] args) throws Exception {
        // Port 0 lets the OS choose a free port; bind to loopback only
        try (ServerSocket server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) {
            Thread.ofPlatform().daemon().start(() -> serve(server));
            int port = server.getLocalPort();
            System.out.println("server listening on a free port: " + (port > 0));

            for (String client : new String[] {"ana", "ben"}) {
                try (Socket s = new Socket(InetAddress.getLoopbackAddress(), port);
                     PrintWriter out = new PrintWriter(s.getOutputStream(), true,
                             StandardCharsets.UTF_8);
                     BufferedReader in = new BufferedReader(new InputStreamReader(
                             s.getInputStream(), StandardCharsets.UTF_8))) {
                    for (String msg : new String[] {"hello from " + client, "bye"}) {
                        out.println(msg);
                        System.out.println(client + " sent \"" + msg + "\", got \""
                                + in.readLine() + "\"");
                    }
                }
            }
            System.out.println("connections accepted: " + connections.get());
        }
    }
}

Output:

Output
server listening on a free port: true
ana sent "hello from ana", got "HELLO FROM ANA"
ana sent "bye", got "BYE"
ben sent "hello from ben", got "HELLO FROM BEN"
ben sent "bye", got "BYE"
connections accepted: 2
  • Port 0 asks the operating system for any free port; getLocalPort() tells you which one. Binding to the loopback address keeps the demo server unreachable from other machines.
  • PrintWriter with auto-flush sends each line immediately. Without flushing, the client would wait forever for a reply to a request still sitting in its own buffer.
  • readLine() returning null means the client closed its side, which ends that connection's loop.

TCP is a stream, not a sequence of messages

TCP keeps bytes in order but does not keep the boundaries between writes. The second program sends "first", "second" and "third" with three separate write calls, waits until they have all arrived, and then calls read once.

Java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class StreamNotMessages {

    public static void main(String[] args) throws Exception {
        InetAddress lo = InetAddress.getLoopbackAddress();
        try (ServerSocket server = new ServerSocket(0, 50, lo);
             Socket client = new Socket(lo, server.getLocalPort());
             Socket conn = server.accept()) {

            // Three separate writes...
            OutputStream out = client.getOutputStream();
            for (String m : new String[] {"first", "second", "third"}) {
                out.write(m.getBytes(StandardCharsets.UTF_8));
                out.flush();
            }
            Thread.sleep(200);                               // let all bytes arrive

            // ...arrive as one undivided run of bytes
            InputStream in = conn.getInputStream();
            byte[] buf = new byte[1024];
            int n = in.read(buf);
            System.out.println("one read() returned " + n + " bytes: \""
                    + new String(buf, 0, n, StandardCharsets.UTF_8) + "\"");

            // Framing: prefix each message with its length
            DataOutputStream dout = new DataOutputStream(out);
            for (String m : new String[] {"first", "second", "third"}) {
                byte[] b = m.getBytes(StandardCharsets.UTF_8);
                dout.writeInt(b.length);
                dout.write(b);
            }
            dout.flush();
            Thread.sleep(200);
            DataInputStream din = new DataInputStream(in);
            for (int i = 0; i < 3; i++) {
                byte[] msg = new byte[din.readInt()];
                din.readFully(msg);                          // read() may return fewer bytes
                System.out.println("framed message " + (i + 1) + ": \""
                        + new String(msg, StandardCharsets.UTF_8) + "\"");
            }
        }
    }
}

Output:

Output
one read() returned 16 bytes: "firstsecondthird"
framed message 1: "first"
framed message 2: "second"
framed message 3: "third"

One read returned all 16 bytes run together; the receiver cannot tell where one message ended. The opposite also happens: a large message can arrive split over several reads. Protocols therefore define framing. Common choices:

  • a delimiter, such as the line breaks used by the echo server;
  • a length prefix, used in the second half of the program;
  • a format that describes its own length, such as HTTP's Content-Length.

With a length prefix, the receiver reads the length with readInt and then exactly that many bytes with readFully, which loops until it has all of them. A plain read(buffer) may return fewer bytes than requested.

Failures and timeouts

Network code spends much of its effort on things going wrong. The program connects to a port where nothing listens, reads from a peer that sends nothing, and reads after the peer has finished sending.

Java
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class Failures {

    public static void main(String[] args) throws Exception {
        InetAddress lo = InetAddress.getLoopbackAddress();

        // Nothing listening: the OS answers immediately with a refusal
        int closedPort;
        try (ServerSocket tmp = new ServerSocket(0, 1, lo)) {
            closedPort = tmp.getLocalPort();
        }
        try (Socket s = new Socket()) {
            s.connect(new InetSocketAddress(lo, closedPort), 2000);
        } catch (ConnectException e) {
            System.out.println("connect to a closed port: ConnectException (" + e.getMessage()
                    + ")");
        }

        try (ServerSocket server = new ServerSocket(0, 50, lo);
             Socket client = new Socket(lo, server.getLocalPort());
             Socket conn = server.accept()) {

            // A peer that sends nothing: without a timeout read() would block forever
            client.setSoTimeout(500);
            long start = System.nanoTime();
            try {
                client.getInputStream().read();
            } catch (SocketTimeoutException e) {
                System.out.println("read with 500 ms timeout: SocketTimeoutException after ~"
                        + Math.round((System.nanoTime() - start) / 1e8) * 100 + " ms");
            }

            // The peer finishes sending: read() returns -1 (end of stream), it does not throw
            conn.shutdownOutput();
            InputStream in = client.getInputStream();
            System.out.println("read after the peer finished sending: " + in.read());
        } catch (IOException e) {
            System.out.println("unexpected: " + e);
        }
    }
}

Output:

Output
connect to a closed port: ConnectException (Connection refused)
read with 500 ms timeout: SocketTimeoutException after ~500 ms
read after the peer finished sending: -1
  • A closed port fails at once with ConnectException: Connection refused. An unreachable host is different: without the 2-second timeout passed to connect, it can block for over a minute while the OS retries.
  • By default, read blocks forever. setSoTimeout makes it throw SocketTimeoutException after the given time; the connection stays usable. Every client socket in production code should have both a connect timeout and a read timeout.
  • When the peer finishes sending (with shutdownOutput or close), read returns -1. That is the normal end of a stream, not an error. A peer that disappears abruptly typically causes SocketException: Connection reset instead.

Small writes, Nagle's algorithm and delayed ACKs

By default TCP uses Nagle's algorithm: while earlier data is unacknowledged, small writes are held back and combined. The receiver, meanwhile, often delays its acknowledgment by up to tens of milliseconds, hoping to piggyback it on a reply. A client that sends each request as two small writes, a 4-byte header and then a body, hits both at once. The program times 50 such requests with the default settings, with TCP_NODELAY, and with one buffered write.

Java
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class NagleLatency {

    // Server: reads a 4-byte header and a 100-byte body, replies with one byte
    static void serve(ServerSocket server) {
        Thread.ofVirtual().start(() -> {
            while (true) {
                try (Socket s = server.accept()) {
                    s.setTcpNoDelay(true);                 // the reply is sent at once
                    DataInputStream in = new DataInputStream(s.getInputStream());
                    OutputStream out = s.getOutputStream();
                    byte[] body = new byte[100];
                    while (true) {
                        in.readInt();
                        in.readFully(body);
                        out.write(1);
                    }
                } catch (Exception e) {
                    if (server.isClosed()) {
                        return;
                    }
                }
            }
        });
    }

    // Client: 50 requests, each sent as two small writes (header, then body)
    static double msPerRequest(int port, boolean noDelay, boolean buffered) throws Exception {
        try (Socket s = new Socket(InetAddress.getLoopbackAddress(), port)) {
            s.setTcpNoDelay(noDelay);
            OutputStream raw = s.getOutputStream();
            DataOutputStream out = new DataOutputStream(buffered
                    ? new BufferedOutputStream(raw) : raw);
            InputStream in = s.getInputStream();
            byte[] body = new byte[100];
            long t0 = System.nanoTime();
            for (int i = 0; i < 50; i++) {
                out.writeInt(100);                         // write 1: 4 bytes
                out.write(body);                           // write 2: 100 bytes
                out.flush();                               // buffered: one 104-byte write
                in.read();                                 // wait for the reply
            }
            return (System.nanoTime() - t0) / 50 / 1e6;
        }
    }

    public static void main(String[] args) throws Exception {
        try (ServerSocket server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) {
            serve(server);
            try (Socket probe = new Socket(InetAddress.getLoopbackAddress(),
                    server.getLocalPort())) {
                System.out.println("defaults: TCP_NODELAY=" + probe.getTcpNoDelay()
                        + ", SO_KEEPALIVE=" + probe.getKeepAlive() + ", SO_LINGER="
                        + probe.getSoLinger() + ", SO_TIMEOUT=" + probe.getSoTimeout());
            }
            int port = server.getLocalPort();
            msPerRequest(port, true, false);                // warm-up
            System.out.printf("two writes, Nagle on (default):  %6.2f ms per request%n",
                    msPerRequest(port, false, false));
            System.out.printf("two writes, TCP_NODELAY = true:  %6.2f ms per request%n",
                    msPerRequest(port, true, false));
            System.out.printf("one buffered write, Nagle on:    %6.2f ms per request%n",
                    msPerRequest(port, false, true));
        }
    }
}

Output:

Output
defaults: TCP_NODELAY=false, SO_KEEPALIVE=false, SO_LINGER=-1, SO_TIMEOUT=0
two writes, Nagle on (default):   43.09 ms per request
two writes, TCP_NODELAY = true:    0.08 ms per request
one buffered write, Nagle on:      0.16 ms per request
  • The defaults are Nagle on (TCP_NODELAY=false), no keep-alive, no linger and no read timeout.
  • With two writes per request, each request took over 40 ms on loopback, where the network itself takes microseconds. The body waited for the header's acknowledgment, which Linux delayed by about 40 ms.
  • setTcpNoDelay(true) removed the delay: well under a millisecond per request. Request-response protocols such as HTTP clients, database drivers and RPC frameworks normally set it.
  • Sending the whole request in one write, through a BufferedOutputStream and flush(), was also well under a millisecond with Nagle left on. Writing complete messages at once is the better fix, because it also saves system calls.
Socket options worth knowing
OptionMethodDefaultEffect
TCP_NODELAYsetTcpNoDelayfalseSends small writes at once instead of combining them
SO_TIMEOUTsetSoTimeout0 (forever)Maximum time a read blocks
SO_KEEPALIVEsetKeepAlivefalseProbes idle connections; the first probe typically comes after two hours, so applications usually send their own heartbeats
SO_LINGERsetSoLinger-1 (off)Controls whether close waits for unsent data
SO_RCVBUF, SO_SNDBUFsetReceiveBufferSize, setSendBufferSizeChosen by the OSKernel buffer sizes; larger buffers help on fast, long-distance links
SO_REUSEADDRsetReuseAddressPlatform-specificLets a restarted server bind a port whose old connections are still closing

The ServerSocket constructor's second argument is the backlog: how many completed connections the kernel queues before your code calls accept(). The last two programs pass 50, which is also the default. A server that accepts slowly under load sees clients time out even though it is running, which a larger backlog or a faster accept loop fixes.

Buffer your streams

Every write on a socket's raw stream is a system call. The program sends 200,000 four-byte integers through a DataOutputStream, once directly on the socket stream and once through an 8 KB BufferedOutputStream, after a warm-up round; a rough measurement on a 2-CPU Linux machine.

Java
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SmallWrites {

    public static void main(String[] args) throws Exception {
        InetAddress lo = InetAddress.getLoopbackAddress();
        try (ServerSocket server = new ServerSocket(0, 50, lo)) {
            int port = server.getLocalPort();

            // Unbuffered small writes: one system call (and maybe one packet) each
            Thread.ofVirtual().start(() -> {
                while (!server.isClosed()) {
                    try (Socket s = server.accept(); InputStream in = s.getInputStream()) {
                        in.transferTo(OutputStream.nullOutputStream());
                    } catch (Exception e) {
                        return;
                    }
                }
            });
            for (int round = 0; round < 2; round++) {
                for (boolean buffered : new boolean[] {false, true}) {
                    try (Socket c = new Socket(lo, port)) {
                        OutputStream raw = c.getOutputStream();
                        DataOutputStream out = new DataOutputStream(buffered
                                ? new BufferedOutputStream(raw, 8192) : raw);
                        long t0 = System.nanoTime();
                        for (int i = 0; i < 200000; i++) {
                            out.writeInt(i);
                        }
                        out.flush();
                        long ms = (System.nanoTime() - t0) / 1000000;
                        if (round == 1) {                   // round 0 is a warm-up
                            System.out.printf("200,000 writeInt calls, %-10s %5d ms%n",
                                    buffered ? "buffered:" : "unbuffered:", ms);
                        }
                    }
                }
            }
        }
    }
}

Output of the write timing run:

Output
200,000 writeInt calls, unbuffered:    89 ms
200,000 writeInt calls, buffered:      8 ms

The unbuffered version made 200,000 system calls and was several times slower than the buffered one, which made about a hundred. Wrap socket streams in buffered streams, and call flush() when a message is complete, since the buffer otherwise holds the last bytes back.

Which approach to use

Choosing TCP settings and APIs
SituationUse
A simple server with many clients on Java 21+ServerSocket plus a virtual thread per connection
Message boundariesLine delimiters or a length prefix with readFully
Every client socketA connect timeout and setSoTimeout
Request-response protocolsWhole messages per write, and TCP_NODELAY
Many small valuesBufferedOutputStream and an explicit flush()
Thousands of connections without virtual threadsNIO selectors
HTTPThe HttpClient, not raw sockets

Closing deserves the same care as connecting. shutdownOutput() sends the end-of-stream marker while keeping the socket open for reading, so a client can say "that was my whole request" and still read the reply; this is called a half-close. close() ends both directions and releases the port. A peer that vanishes without closing, because its process was killed or its network failed, leaves the other side either with "Connection reset" on the next read or write, or with nothing at all until a timeout fires, which is one more reason every socket needs setSoTimeout. Finally, closing a socket that another thread is blocked reading makes that read throw SocketException: Socket closed, which is the usual way to stop a blocked reader.

For datagrams without connections, see UDP sockets. To encrypt the connection, see SSL/TLS sockets. For many connections on few threads without virtual threads, see NIO selectors.