Java ServerSocket
A Java ServerSocket is the server side of a TCP connection. It listens on a port and waits for clients; each time a client connects, accept() hands you a new Socket for talking to that one client.
Every TCP server written in Java, from a chat server to a web server, is built on this idea. In this lesson you will create a Java ServerSocket, accept and serve a client, choose ports and bind addresses, serve many clients at once with threads, use accept timeouts, shut a server down cleanly and finally build a tiny working HTTP server.
How a ServerSocket Works
A ServerSocket never sends or receives data itself. Its only job is to accept connections. The real conversation happens on the Socket objects that accept() returns, exactly like the client sockets in Java Socket Basics.
| Step | What happens |
|---|---|
| 1. Bind | new ServerSocket(8094) reserves port 8094 and starts listening |
| 2. Accept | accept() blocks until a client connects, then returns a Socket |
| 3. Serve | Read from and write to that Socket |
| 4. Repeat | Call accept() again for the next client |
| 5. Close | serverSocket.close() stops listening; open client sockets are not affected |
Common ServerSocket member | Purpose |
|---|---|
ServerSocket(port) | Listen on a port, on all network interfaces |
ServerSocket(port, backlog, bindAddr) | Also set the queue size and the local address |
ServerSocket() + bind(address, backlog) | Create first, set options, then bind |
accept() | Wait for and return the next client connection |
setSoTimeout(ms) | Limit how long accept() waits |
getLocalPort() | The port the server listens on |
setReuseAddress(true) | Allow a quick restart on the same port |
close() | Stop listening |
Creating Your First Java ServerSocket
This server accepts one client, echoes every line it receives and stops when the client disconnects. To keep the example self-contained, a client runs in a background thread of the same program.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class EchoServerOnce {
public static void main(String[] args) throws Exception {
try (ServerSocket server = new ServerSocket(8094)) {
System.out.println("Server listening on port " + server.getLocalPort());
// A client in a background thread, so the example runs on its own
Thread clientThread = Thread.ofPlatform().start(EchoServerOnce::runClient);
// accept() blocks until a client connects, then returns a new Socket
try (Socket client = server.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
PrintWriter out = new PrintWriter(client.getOutputStream(), true, StandardCharsets.UTF_8)) {
System.out.println("Server accepted a client from " + client.getInetAddress().getHostAddress());
String line;
while ((line = in.readLine()) != null) { // until the client closes
System.out.println("Server received: " + line);
out.println("echo: " + line);
}
System.out.println("Client disconnected");
}
clientThread.join();
}
}
static void runClient() {
try (Socket socket = new Socket("localhost", 8094);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
for (String message : new String[] {"hello", "how are you?"}) {
out.println(message);
System.out.println("Client got: " + in.readLine());
}
} catch (Exception e) {
System.out.println("Client error: " + e);
}
}
}
Output:
Server listening on port 8094
Server accepted a client from 127.0.0.1
Server received: hello
Client got: echo: hello
Server received: how are you?
Client got: echo: how are you?
Client disconnected
How it works:
new ServerSocket(8094)binds port 8094. If another program already uses the port, it throwsBindException.server.accept()blocks until the client thread connects, then returns aSocketconnected to that client.- The server reads lines with
readLine()until it returnsnull, which means the client closed its side. - The client's socket and the accepted socket are two ends of the same connection: what one writes, the other reads.
- Closing the accepted
Socketends this conversation; closing theServerSocket(by try-with-resources at the end) stops listening.
Choosing the Port and Bind Address
The constructor arguments decide where the server listens and how many waiting connections it queues.
| Argument | Meaning |
|---|---|
port | Port number from 1 to 65535, or 0 to let the OS choose a free port |
backlog | How many connections may wait in the queue before accept() takes them (a hint to the OS, default 50) |
bindAddr | Which local address to listen on; null means every interface |
Binding to InetAddress.getLoopbackAddress() (127.0.0.1) makes the server reachable only from the same machine. That is safer for development tools, admin consoles and tests.
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
public class BindOptions {
public static void main(String[] args) throws Exception {
// 1. Port 0: let the operating system pick a free port
try (ServerSocket anyPort = new ServerSocket(0)) {
System.out.println("OS picked a port: " + (anyPort.getLocalPort() > 0));
System.out.println("Listening on all interfaces: " + anyPort.getInetAddress().isAnyLocalAddress());
}
// 2. Port, backlog and bind address: only local programs can connect
try (ServerSocket localOnly = new ServerSocket(8094, 100, InetAddress.getLoopbackAddress())) {
System.out.println("Bound to: " + localOnly.getLocalSocketAddress());
// 3. The same port cannot be used twice at the same time
try (ServerSocket clash = new ServerSocket(8094, 100, InetAddress.getLoopbackAddress())) {
System.out.println("This line never runs");
} catch (java.net.BindException e) {
System.out.println("Second bind failed: " + e.getMessage());
}
}
// 4. Create unbound, set options, then bind
try (ServerSocket server = new ServerSocket()) {
server.setReuseAddress(true); // allow quick restarts on the same port
System.out.println("Bound before bind()? " + server.isBound());
server.bind(new InetSocketAddress("localhost", 8094), 50);
System.out.println("Bound after bind()? " + server.isBound());
}
}
}
Output:
OS picked a port: true
Listening on all interfaces: true
Bound to: localhost/127.0.0.1:8094
Second bind failed: Address already in use
Bound before bind()? false
Bound after bind()? true
How it works:
- Port
0asks the OS for any free port. Tests often use this so they never clash with another program;getLocalPort()tells you which port was picked. - Without a bind address, the server listens on the "any" address (
0.0.0.0), so other machines on the network can connect. - The second
ServerSocketon port 8094 fails withBindException: Address already in use, because only one server can listen on a port and address at a time. new ServerSocket()creates an unbound server. This lets you set options such assetReuseAddress(true)before callingbind().
Note: On Linux and macOS, ports below 1024 need administrator rights. Use ports such as 8080 or 8094 during development.
Handling Multiple Clients with Threads
A server that handles one client at a time makes every other client wait. The standard fix is to give each accepted Socket its own thread, while the main loop goes straight back to accept(). Since Java 21, virtual threads make one thread per client cheap even with thousands of connections.
This example starts the same server twice, first sequential and then with a thread per client, and measures how long 5 clients that each need 300 ms of work take to be served.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiClientServer {
// Handle one client: reply to each line after 300 ms of "work"
static void handle(Socket client) {
try (client;
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
PrintWriter out = new PrintWriter(client.getOutputStream(), true, StandardCharsets.UTF_8)) {
String line;
while ((line = in.readLine()) != null) {
Thread.sleep(300);
out.println("done: " + line);
}
} catch (IOException | InterruptedException e) {
// client gone
}
}
// Accept clients forever; give each one its own virtual thread
static void serve(ServerSocket server, boolean oneThreadPerClient) {
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
while (true) {
Socket client = server.accept();
if (oneThreadPerClient) pool.submit(() -> handle(client));
else handle(client); // sequential: the next accept() waits for this client
}
} catch (IOException e) {
// server socket closed: stop accepting
}
}
// Start 5 clients at once and measure how long until all are answered
static long timeFiveClients() throws Exception {
long start = System.nanoTime();
List<Thread> clients = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
int id = i;
clients.add(Thread.ofVirtual().start(() -> {
try (Socket s = new Socket("localhost", 8094);
PrintWriter out = new PrintWriter(s.getOutputStream(), true, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8))) {
out.println("job " + id);
in.readLine();
} catch (IOException e) {
System.out.println("client error " + e);
}
}));
}
for (Thread t : clients) t.join();
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) throws Exception {
for (boolean threaded : new boolean[] {false, true}) {
try (ServerSocket server = new ServerSocket(8094)) {
Thread.ofPlatform().start(() -> serve(server, threaded));
long ms = timeFiveClients();
System.out.printf("%-26s 5 clients answered in %s%n",
threaded ? "Thread per client:" : "Sequential (one by one):",
ms >= 1500 ? "1.5 s or more" : ms < 1000 ? "under 1 s" : "1 to 1.5 s");
}
}
}
}
Output:
Sequential (one by one): 5 clients answered in 1.5 s or more
Thread per client: 5 clients answered in under 1 s
How it works:
serve()is the classic accept loop:while (true) { Socket client = server.accept(); ... }.- In sequential mode,
handle(client)runs on the accept thread, so client 2 is not even accepted until client 1 is finished. Five clients × 300 ms add up to about 1.5 seconds. - In threaded mode,
pool.submit(() -> handle(client))runs each client on its own virtual thread fromExecutors.newVirtualThreadPerTaskExecutor(), so all five are served at the same time. - The loop ends when the
ServerSocketis closed:accept()then throws anIOException, which breaks out ofwhile (true). try (client; ...)closes the client socket whenhandle()returns, even if an exception occurs.
Note: For CPU-heavy work or very old Java versions, use a fixed thread pool instead of one thread per client, so a flood of connections cannot create unlimited platform threads.
Accept Timeouts and Stopping a Server
accept() normally blocks forever. There are two ways to get a blocked server thread back:
| Technique | Result |
|---|---|
setSoTimeout(ms) before accept() | accept() throws SocketTimeoutException after the timeout; the server stays open |
serverSocket.close() from another thread | accept() throws SocketException: Socket closed; the server is finished |
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
public class AcceptTimeout {
public static void main(String[] args) throws Exception {
// 1. accept() with a timeout
try (ServerSocket server = new ServerSocket(8094)) {
server.setSoTimeout(1000); // wait at most 1 s for a client
try {
server.accept();
} catch (SocketTimeoutException e) {
System.out.println("No client in time: " + e.getMessage());
}
System.out.println("Server still open? " + !server.isClosed());
}
// 2. Stopping a blocked accept() by closing the server from another thread
ServerSocket server = new ServerSocket(8094);
Thread acceptor = Thread.ofPlatform().start(() -> {
try {
Socket client = server.accept();
client.close();
} catch (SocketException e) {
System.out.println("accept() ended: " + e.getMessage());
} catch (Exception e) {
System.out.println("Unexpected: " + e);
}
});
Thread.sleep(300); // let the thread block in accept()
server.close(); // makes accept() throw SocketException
acceptor.join();
System.out.println("Server closed? " + server.isClosed());
}
}
Output:
No client in time: Accept timed out
Server still open? true
accept() ended: Socket closed
Server closed? true
How it works:
- With
setSoTimeout(1000),accept()gives up after one second. The server remains usable, so a loop can check a "stop" flag and then callaccept()again. - In part 2, the acceptor thread blocks in
accept(). Callingserver.close()from the main thread wakes it up withSocketException, which is the normal way to shut down a server's accept loop. catch (SocketException e)must come before the generalcatch (Exception e), becauseSocketExceptionis more specific.
Real-World Example: A Tiny HTTP Server with ServerSocket
HTTP is just text over a TCP connection, so you can build a working web server from a ServerSocket. This TinyHttpServer:
- accepts connections on a dedicated acceptor thread,
- handles each request on a virtual thread,
- parses the request line (
GET /hello?name=Ravi HTTP/1.1) and skips the headers, - routes
/helloand/stats, and returns404and405for everything else, - writes a correct HTTP/1.1 response with
Content-Length, - shuts down cleanly through
close().
The main method tests the server with Java's own HttpClient.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
// A minimal HTTP/1.1 server built directly on ServerSocket
public class TinyHttpServer implements AutoCloseable {
private final ServerSocket serverSocket;
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
private final AtomicInteger requestCount = new AtomicInteger();
public TinyHttpServer(int port) throws IOException {
serverSocket = new ServerSocket(port, 100, InetAddress.getLoopbackAddress());
Thread.ofPlatform().name("acceptor").start(this::acceptLoop);
}
private void acceptLoop() {
while (!serverSocket.isClosed()) {
try {
Socket client = serverSocket.accept();
client.setSoTimeout(5000); // drop clients that never send a request
workers.submit(() -> handle(client));
} catch (SocketException e) {
return; // close() was called
} catch (IOException e) {
System.out.println("accept failed: " + e.getMessage());
}
}
}
private void handle(Socket client) {
try (client) {
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream(), StandardCharsets.US_ASCII));
String requestLine = in.readLine(); // e.g. "GET /hello?name=Ravi HTTP/1.1"
if (requestLine == null) return;
while (!in.readLine().isEmpty()) { } // skip headers until the blank line
requestCount.incrementAndGet();
String[] parts = requestLine.split(" ");
String method = parts[0];
URI target = URI.create(parts[1]);
if (!method.equals("GET")) {
respond(client, 405, "Method Not Allowed", "Only GET is supported\n");
} else if (target.getPath().equals("/hello")) {
String query = target.getRawQuery() == null ? "" : target.getRawQuery();
String name = query.startsWith("name=")
? URLDecoder.decode(query.substring(5), StandardCharsets.UTF_8) : "guest";
respond(client, 200, "OK", "Hello, " + name + "!\n");
} else if (target.getPath().equals("/stats")) {
respond(client, 200, "OK", "requests=" + requestCount.get() + "\n");
} else {
respond(client, 404, "Not Found", "No page at " + target.getPath() + "\n");
}
} catch (IOException | RuntimeException e) {
// bad or interrupted request: just close the connection
}
}
private static void respond(Socket client, int status, String reason, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
String head = "HTTP/1.1 " + status + " " + reason + "\r\n"
+ "Content-Type: text/plain; charset=utf-8\r\n"
+ "Content-Length: " + bytes.length + "\r\n"
+ "Connection: close\r\n"
+ "\r\n";
OutputStream out = client.getOutputStream();
out.write(head.getBytes(StandardCharsets.US_ASCII));
out.write(bytes);
out.flush();
}
@Override
public void close() throws IOException {
serverSocket.close(); // stops the accept loop
workers.close(); // waits for running requests to finish
}
public static void main(String[] args) throws Exception {
try (TinyHttpServer server = new TinyHttpServer(8094);
HttpClient client = HttpClient.newHttpClient()) {
String[] paths = {"/hello?name=Ravi%20Kumar", "/hello", "/missing", "/stats"};
for (String path : paths) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8094" + path)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.printf("GET %-24s -> %d %s", path, response.statusCode(), response.body());
}
HttpRequest post = HttpRequest.newBuilder(URI.create("http://localhost:8094/hello"))
.POST(HttpRequest.BodyPublishers.noBody()).build();
HttpResponse<String> postResponse = client.send(post, HttpResponse.BodyHandlers.ofString());
System.out.printf("POST %-23s -> %d %s", "/hello", postResponse.statusCode(), postResponse.body());
}
System.out.println("Server stopped");
}
}
Output:
GET /hello?name=Ravi%20Kumar -> 200 Hello, Ravi Kumar!
GET /hello -> 200 Hello, guest!
GET /missing -> 404 No page at /missing
GET /stats -> 200 requests=4
POST /hello -> 405 Only GET is supported
Server stopped
How it works:
- Separate acceptor thread. The constructor binds to the loopback address and starts
acceptLoop()on a thread namedacceptor, sonew TinyHttpServer(8094)returns immediately. - Protection from idle clients.
client.setSoTimeout(5000)means a client that connects but never sends a request is dropped after 5 seconds instead of holding a thread forever. - Reading the request. An HTTP request starts with a request line, then header lines, then an empty line. The server reads the first line, then skips lines until it finds the empty one.
- Routing.
URI.create(parts[1])splits the target into a path and a query.URLDecoderturnsRavi%20Kumarback intoRavi Kumar, as explained in the Java URI class lesson. - Writing the response. The status line, headers and blank line use
\r\nline endings, as HTTP requires.Content-Lengthis the size of the body in bytes, andConnection: closetells the client that the server closes the socket after each response. - Thread-safe counter. Requests are handled on different threads, so
requestCountis anAtomicInteger. The/statspage counts its own request, which is why it reports 4. - Clean shutdown.
close()closes theServerSocket(ending the accept loop throughSocketException) and then closes the executor, which waits for requests that are still running.
Note: This server shows how HTTP works under the hood. For real applications, use a tested server such as the JDK's
com.sun.net.httpserver.HttpServer, Jetty, Tomcat or Spring Boot, which handle keep-alive, chunked bodies, HTTPS and many edge cases.