Java Server Sockets: Serving Multiple Clients with Threads and Virtual Threads
Write TCP servers in Java: ServerSocket, binding and backlog, the accept loop, an echo server, serving many clients concurrently with one virtual thread per connection, half-closing a connection with shutdownOutput, and shutting a server down cleanly.
kvi5hnuCode Sprout team member9 min readOn this page
Article 48 connected a client to an existing server. Now we write the server: a program that waits for clients to connect to its port, then talks to each of them according to some protocol.
A first server
A ServerSocket claims a port and listens on it:
var server = new ServerSocket(8189);
Socket incoming = server.accept();
accept() blocks until a client connects, then returns a Socket for that connection, the same kind of object a client gets. From here, client and server are symmetric. What the server writes to its output stream arrives in the client's input stream, and vice versa.
An echo server is the networking equivalent of "Hello, World". It greets the client and repeats every line it receives:
try (var server = new ServerSocket(8189);
Socket incoming = server.accept();
var in = new Scanner(incoming.getInputStream(), StandardCharsets.UTF_8);
var out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(),
StandardCharsets.UTF_8), true /* autoFlush */)) {
out.println("Hello! Enter BYE to exit.");
while (in.hasNextLine()) {
String line = in.nextLine();
out.println("Echo: " + line);
if (line.strip().equals("BYE")) break;
}
}
Run it and connect with nc localhost 8189 (or telnet localhost 8189). Note the autoFlush flag on the PrintWriter: without it, each reply would stay in the buffer and the client would wait forever.
Every real server follows the same pattern: read a request from the input stream, decode it, compute or fetch the answer, and write it to the output stream.
Choosing where to listen
Port 8189 is arbitrary, chosen because no standard service uses it. Pass port 0 to let the operating system pick a free port, and ask for it with getLocalPort(). Tests do this to avoid conflicts, and so does the demo.
By default, new ServerSocket(port) listens on all network interfaces of the machine. If the machine is connected to a network, anyone who can reach it can connect. For servers meant only for local use, bind to the loopback address:
var server = new ServerSocket(port, 50, InetAddress.getLoopbackAddress());
The middle argument is the backlog, the maximum number of connections the operating system queues while your program hasn't yet called accept. For more control, create an unbound socket, set options, then bind:
var server = new ServerSocket();
server.setReuseAddress(true); // allow restarting quickly on the same port
server.bind(new InetSocketAddress(port), 100);
SO_REUSEADDR matters after a restart: for a while after a server closes, the operating system keeps old connections in the TIME_WAIT state, and binding to the same port may fail with "Address already in use".
Serving multiple clients
The first server has a serious flaw. It handles one client, and while it does, nobody else is served. Even a server with an outer loop around accept would serve clients strictly one after another, so a single slow client would block everybody.
The classic solution is one thread per connection. The main thread does nothing but accept connections and hand each one to a new thread:
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
while (true) {
Socket incoming = server.accept();
pool.submit(() -> serve(incoming));
}
}
serve contains the conversation from the echo example, with the socket in its own try-with-resources so it's closed when the conversation ends.
With platform threads, one thread per connection used to be a scalability problem. Each thread reserves a large stack and is an operating system resource, so servers with tens of thousands of connections needed thread pools, or non-blocking I/O with selectors, which is much harder to write. Virtual threads (Java 21) remove that tension. They're cheap enough to create one per connection, even for hundreds of thousands of connections, and when a virtual thread blocks on socket I/O, it releases its carrier thread so that other virtual threads can run. The simple blocking style of the code above becomes the scalable choice. (The concurrency part of this course covers virtual threads in detail.)
The demo starts 500 clients at once against an echo server with this design and checks that each one gets its own echoes back.
Half-close
Sometimes a client sends a request whose length it doesn't announce in advance, for example data it streams from somewhere else. With a file, you'd signal the end by closing it. But closing a socket closes the whole connection, including the direction in which the response should come back.
The half-close solves this. shutdownOutput() closes only the outgoing direction. The other side sees end-of-stream, while the socket stays open for reading:
try (var socket = new Socket(host, port)) {
var out = socket.getOutputStream();
out.write(requestBytes);
out.flush();
socket.shutdownOutput(); // tells the server: request complete
byte[] response = socket.getInputStream().readAllBytes();
}
The server simply reads until end-of-stream (for example with readAllBytes), then sends its answer. After shutdownOutput, any further write on that socket throws a SocketException. shutdownInput() is the mirror image, and isOutputShutdown() and isInputShutdown() report the state. Half-close fits one-shot request/response protocols. Protocols with many exchanges per connection need explicit message framing instead, such as length prefixes or delimiter lines.
Stopping a server
accept() blocks, so how does a server stop? Closing the ServerSocket from another thread makes the blocked accept throw a SocketException ("Socket closed"), which ends the loop. Leaving the try-with-resources block of the executor then waits for the conversations in progress to finish. New connection attempts are refused from that point on.
The program
The demo binds an echo server to the loopback interface on a free port, with a backlog of 100. Its accept loop runs on a platform thread and hands each connection to a virtual thread. A single client has a short conversation. Then 500 clients, all virtual threads released at the same moment by a latch, talk to the server concurrently, and the program checks the echoes and that several conversations really overlapped. A second server counts words in a request that the client ends with shutdownOutput. Finally, both servers are shut down by closing their sockets.
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class Solution {
static final AtomicInteger active = new AtomicInteger();
static final AtomicInteger peak = new AtomicInteger();
/** The conversation with one client: greet, echo lines, stop at BYE. */
static void serveEcho(Socket incoming) {
int now = active.incrementAndGet();
peak.accumulateAndGet(now, Math::max);
try (incoming;
var in = new Scanner(incoming.getInputStream(), StandardCharsets.UTF_8);
var out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(), StandardCharsets.UTF_8), true)) {
out.println("Hello! Enter BYE to exit.");
while (in.hasNextLine()) {
String line = in.nextLine();
out.println("Echo: " + line);
if (line.strip().equals("BYE")) break;
}
} catch (IOException e) {
System.out.println("client error: " + e.getMessage());
} finally {
active.decrementAndGet();
}
}
/** Reads until end of stream, then answers: needs the client to half-close. */
static void serveWordCount(Socket incoming) {
try (incoming) {
String text = new String(incoming.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
long words = text.isBlank() ? 0 : text.strip().split("\\s+").length;
var out = incoming.getOutputStream();
out.write((words + " words, " + text.length() + " chars\n").getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
System.out.println("client error: " + e.getMessage());
}
}
/** Accept loop: one virtual thread per connection; ends when the server socket is closed. */
static Thread startServer(ServerSocket server, java.util.function.Consumer<Socket> handler) {
return Thread.ofPlatform().name("acceptor").start(() -> {
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
while (true) {
Socket incoming = server.accept();
pool.submit(() -> handler.accept(incoming));
}
} catch (SocketException e) {
System.out.println("accept loop ended: " + e.getMessage());
} catch (IOException e) {
System.out.println("server error: " + e.getMessage());
}
});
}
static List<String> talk(int port, List<String> lines) throws IOException {
var replies = new ArrayList<String>();
try (var s = new Socket(InetAddress.getLoopbackAddress(), port);
var in = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));
var out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8), true)) {
s.setSoTimeout(5000);
replies.add(in.readLine()); // the greeting
for (String line : lines) {
out.println(line);
replies.add(in.readLine());
}
}
return replies;
}
public static void main(String[] args) throws Exception {
var echo = new ServerSocket();
echo.setReuseAddress(true);
echo.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 100); // backlog 100
Thread acceptor = startServer(echo, Solution::serveEcho);
System.out.println("--- one client ---");
talk(echo.getLocalPort(), List.of("Hi there", " BYE ")).forEach(System.out::println);
System.out.println("--- 500 clients at the same time ---");
int clients = 500;
var start = new CountDownLatch(1);
var results = new ConcurrentHashMap<Integer, List<String>>();
try (var clientPool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < clients; i++) {
int id = i;
clientPool.submit(() -> {
start.await();
results.put(id, talk(echo.getLocalPort(), List.of("client " + id, "BYE")));
return null;
});
}
start.countDown();
}
long correct = results.entrySet().stream()
.filter(e -> e.getValue().get(1).equals("Echo: client " + e.getKey())).count();
System.out.println(results.size() + " conversations, " + correct + " correct echoes, "
+ "more than one at once: " + (peak.get() > 1));
System.out.println("--- half-close ---");
var counter = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
{
Thread countAcceptor = startServer(counter, Solution::serveWordCount);
try (var s = new Socket(InetAddress.getLoopbackAddress(), counter.getLocalPort())) {
var out = s.getOutputStream();
out.write("the quick brown fox\njumps over\nthe lazy dog".getBytes(StandardCharsets.UTF_8));
out.flush();
s.shutdownOutput(); // "end of request", but keep reading
System.out.println("output shut down: " + s.isOutputShutdown() + ", input open: " + !s.isInputShutdown());
System.out.print("server says: " + new String(s.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
try {
out.write(1);
} catch (SocketException e) {
System.out.println("writing after shutdownOutput: " + e.getClass().getSimpleName());
}
}
counter.close();
countAcceptor.join();
}
System.out.println("--- shutting down ---");
echo.close(); // makes accept() throw, ending the loop
acceptor.join();
System.out.println("server closed: " + echo.isClosed());
try (var s = new Socket()) {
s.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), echo.getLocalPort()), 1000);
} catch (ConnectException e) {
System.out.println("new connection refused");
}
}
}
--- one client ---
Hello! Enter BYE to exit.
Echo: Hi there
Echo: BYE
--- 500 clients at the same time ---
500 conversations, 500 correct echoes, more than one at once: true
--- half-close ---
output shut down: true, input open: true
server says: 9 words, 43 chars
writing after shutdownOutput: SocketException
accept loop ended: Socket closed
--- shutting down ---
accept loop ended: Socket closed
server closed: true
new connection refused
Common questions
Why does my server say "Address already in use"?
Either another process (or a previous run that is still alive) is listening on the port, or old connections are in TIME_WAIT after a restart. Check with lsof -i :8189 (macOS and Linux) or netstat -ano (Windows). For the restart case, set SO_REUSEADDR before binding.
How many clients can a server handle?
With virtual threads, the limit is usually memory and the operating system's file descriptor limit (ulimit -n, often 256 or 1024 by default on desktops), not threads. Each connection needs a descriptor. Raise the limit for real servers.
How do I make my server reachable from other machines?
Bind to all interfaces (the default, or 0.0.0.0), allow the port in the host's firewall, and, from outside a home or corporate network, configure port forwarding or deploy where a public address exists. For local development, bind to loopback so others can't reach you.
How do I find which client is connected?
socket.getInetAddress() and getPort(), or getRemoteSocketAddress(). Behind a proxy or load balancer, you see the proxy's address; the original client then comes in a header such as X-Forwarded-For, at the HTTP level.
Should I write my own server protocol or use HTTP? Use HTTP (articles 53–55) or an established protocol unless you have a good reason. It passes firewalls and proxies, has tools for debugging, and comes with libraries for TLS, authentication and framing. Custom TCP protocols make sense for low-latency or very specialized traffic.
API reference
| API | Purpose |
|---|---|
new ServerSocket(port), ServerSocket(port, backlog, bindAddress) | listen on a port (0 = any free port) |
new ServerSocket() + bind(SocketAddress, backlog) | bind after setting options |
ServerSocket.setReuseAddress(true) | allow rebinding a port in TIME_WAIT |
ServerSocket.accept() | wait for and return the next connection |
ServerSocket.getLocalPort(), close(), isClosed() | port, shutdown, state |
Executors.newVirtualThreadPerTaskExecutor() | one virtual thread per submitted task (Java 21) |
Thread.ofVirtual().start(runnable) | start a single virtual thread |
Socket.shutdownOutput(), shutdownInput() | half-close one direction |
Socket.isOutputShutdown(), isInputShutdown() | half-close state |
Summary
ServerSocketlistens on a port, andaccept()returns aSocketfor each new client.- Bind to the loopback address for local-only servers. Use port 0 to get any free port, and set the backlog and
SO_REUSEADDRas needed. - Serve each connection on its own thread. With virtual threads, that simple blocking design scales to very many connections.
- Catch exceptions per connection, use read timeouts, and expect clients to vanish.
shutdownOutput()half-closes a connection: the peer sees end-of-stream, and you can still read the response.- Close the
ServerSocketto stop the accept loop.
Practice Questions
Why does a server that calls accept() in a loop, and handles each client before accepting the next, perform badly?
While one client is being served, nobody else is accepted, so a slow or idle client blocks all others. Handling each accepted socket on its own thread, ideally a virtual thread, lets the main loop return to accept immediately.
What advantage do virtual threads bring to a thread-per-connection server?
Virtual threads are cheap to create and to block. When a virtual thread waits for socket I/O, it gives up its carrier thread, so a few platform threads can run a very large number of connections. You keep the straightforward blocking code while scaling like an asynchronous server.
A client sends data of unknown length and then wants to read the server's reply. Why can't it just close the output stream, and what should it do instead?
Closing a socket's output stream closes the whole socket, so the reply could no longer be read. Calling socket.shutdownOutput() closes only the sending direction. The server reads until end-of-stream, then replies, and the client reads the reply on the still-open input side.
Your server runs on a laptop in a café, and someone else connects to it. How do you prevent that?
new ServerSocket(port) listens on all interfaces. Bind to the loopback interface instead, for example new ServerSocket(port, 50, InetAddress.getLoopbackAddress()). Then only programs on the same machine can connect. For servers that must be reachable, add authentication and encryption (article 50).
How do you stop a server thread that's blocked in accept()?
Call close() on the ServerSocket from another thread. The blocked accept throws a SocketException, which the accept loop treats as the signal to end. If the loop uses an executor in try-with-resources, leaving the block waits for the active conversations to finish.
Previous: Java Sockets: Connecting to a Server, Timeouts and InetAddress
Next: Interruptible Sockets and TLS in Java: SocketChannel, Virtual Threads and SSLSocket
Related reading
- Java File Locking: FileLock, Shared and Exclusive Locks
- Java Parallel Streams: When They Help, Ordering and Thread Safety
- Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
- Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
- Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.