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.
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 ServerSocketaccept()SocketSocketInputStreamOutputStream
| API | Since | Best for |
|---|---|---|
SocketServerSocket | Java 1.0 | Simple blocking clients and servers |
SocketChannelSelector | Java 1.4 (NIO) | Many connections on few threads; see |
Reimplemented Socket | Java 13 (JEP 353) | Same API, simpler implementation, ready for virtual threads |
| Virtual threads | Java 21 (JEP 444) | Blocking code that scales to many connections |
SSLSocket | Java 1.4 (JSSE) | Encrypted TCP; see |
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 ServerSocketaccept()SocketSocket
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.
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:
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;
tells you which one. Binding to the loopback address keeps the demo server unreachable from other machines.getLocalPort() 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.PrintWriter returningreadLine() means the client closed its side, which ends that connection's loop.null
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 writeread
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:
one read() returned 16 bytes: "firstsecondthird"
framed message 1: "first"
framed message 2: "second"
framed message 3: "third"
One read
- 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 readIntreadFullyread(buffer)
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.
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:
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
. An unreachable host is different: without the 2-second timeout passed toConnectException: Connection refused , it can block for over a minute while the OS retries.connect - By default,
blocks forever.read makes it throwsetSoTimeout after the given time; the connection stays usable. Every client socket in production code should have both a connect timeout and a read timeout.SocketTimeoutException - When the peer finishes sending (with
orshutdownOutput ),close returns -1. That is the normal end of a stream, not an error. A peer that disappears abruptly typically causesread instead.SocketException: Connection reset
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
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:
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 (
), no keep-alive, no linger and no read timeout.TCP_NODELAY=false - 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.
removed the delay: well under a millisecond per request. Request-response protocols such as HTTP clients, database drivers and RPC frameworks normally set it.setTcpNoDelay(true)- Sending the whole request in one write, through a
andBufferedOutputStream , 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.flush()
| Option | Method | Default | Effect |
|---|---|---|---|
TCP_NODELAY | setTcpNoDelay | false | Sends small writes at once instead of combining them |
SO_TIMEOUT | setSoTimeout | 0 (forever) | Maximum time a read |
SO_KEEPALIVE | setKeepAlive | false | Probes idle connections; the first probe typically comes after two hours, so applications usually send their own heartbeats |
SO_LINGER | setSoLinger | -1 (off) | Controls whether close |
SO_RCVBUFSO_SNDBUF | setReceiveBufferSizesetSendBufferSize | Chosen by the OS | Kernel buffer sizes; larger buffers help on fast, long-distance links |
SO_REUSEADDR | setReuseAddress | Platform-specific | Lets a restarted server bind a port whose old connections are still closing |
The ServerSocketaccept()
Buffer your streams
Every writeDataOutputStreamBufferedOutputStream
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:
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()
Which approach to use
| Situation | Use |
|---|---|
| A simple server with many clients on Java 21+ | ServerSocket |
| Message boundaries | Line delimiters or a length prefix with readFully |
| Every client socket | A connect timeout and setSoTimeout |
| Request-response protocols | Whole messages per write, and TCP_NODELAY |
| Many small values | BufferedOutputStreamflush() |
| Thousands of connections without virtual threads | |
| HTTP | The |
Closing deserves the same care as connecting. shutdownOutput()close()setSoTimeoutSocketException: Socket closed
For datagrams without connections, see