Implementing client-server architecture in Java means splitting your program into a process that listens for requests and one or more processes that send them, then choosing a transport (raw TCP sockets or HTTP), defining a message format, and making the server handle multiple clients without blocking. For a first working system, a TCP socket server using one thread per connection plus a small client class is enough; move to HTTP with a framework or add thread pooling and structured messages as load and requirements grow. The key condition: decide your protocol and concurrency model before writing code, because those two choices shape almost everything else.

This guide walks through a complete minimal implementation, then explains where the simple version breaks and what to change.

What client-server architecture actually requires in Java

The pattern has two roles. The server binds to a port, waits for incoming connections, reads requests, and writes responses. The client opens a connection to a known host and port, sends a request, and reads the response. Java's standard library covers this with java.net.ServerSocket and java.net.Socket for TCP, and java.net.http.HttpClient plus a built-in HTTP server (com.sun.net.httpserver) for HTTP.

Three things must be settled up front:

Transport and protocol. Raw TCP gives you a byte stream and nothing else — you define framing (how the receiver knows where one message ends). HTTP gives you request/response semantics, headers, and status codes for free but adds overhead and constrains the interaction style. Concurrency model. A single-threaded server handles one client at a time. A thread-per-connection server handles many but consumes a thread per client. An event-loop or thread-pool design scales further at the cost of complexity. Java has supported virtual threads since JDK 21 (finalized in JEP 444), which changes the calculus for thread-per-connection designs at high connection counts. Message format. Line-delimited text is the easiest to debug; length-prefixed binary is compact; JSON is a reasonable middle ground. Whatever you choose, both sides must agree exactly.

Everything below builds on these decisions.

Prerequisites: Java version, tools, and project layout

You need a JDK (17 or later is a reasonable floor in 2026; 21 or later if you want virtual threads) and a way to run two processes. No build tool is strictly required for the minimal example — javac and java suffice — but Maven or Gradle makes dependency management easier once you add a JSON library.

Decide on a port that is not already in use. Ports below 1024 typically require elevated privileges on Unix-like systems, so pick something in the registered range such as 5000 or 8080. Also plan your package structure: for the example here, a single package with a Server class and a Client class is enough, and you should run them from separate terminal windows or separate IDE run configurations so you can observe both sides.

One practical note: on many systems, localhost resolves to both IPv4 and IPv6 addresses. If the client fails to connect while the server appears to be running, binding explicitly to 127.0.0.1 on the server and connecting to that same address removes the ambiguity.

Step 1: Define the protocol before writing a line of code

The most common failure in a hand-rolled client-server system is an underspecified protocol. Decide these now:

Request framing. With a line-based protocol, each request is one line terminated by \n. The receiver reads until the newline. Response framing. Same rule: one line per response, terminated by \n. Simpler still: close the connection after each response, so end-of-stream marks the end of the message. Encoding. UTF-8 explicitly, not the platform default. Semantics. For the example, two commands: TIME returns the server's current time, and ECHO returns the text. Anything else returns ERROR unknown command.

Write this down. A protocol that lives only in your head will drift between client and server the first time you refactor one side.

A worked example of the framing problem: if the client sends ECHO hello and the server reads a fixed 1024-byte buffer, a partial read can split the word. Line termination avoids this because the reader loops until it sees the delimiter.

Step 2: Build the TCP server

The server's job is a loop: accept a connection, hand it to a handler, repeat. Here is the minimal thread-per-connection version.

Points worth noticing. setReuseAddress(true) helps when restarting the server quickly during development, because the previous socket may still be in a TIME_WAIT state. Binding to 127.0.0.1 restricts access to the local machine, which is appropriate for development but not for a server other machines must reach — for that, bind to 0.0.0.0 or a specific interface. The try-with-resources block on socket closes the connection when the handler finishes. And because each connection gets its own thread, a slow or hung client does not block the accept loop.

The concurrency detail that bites people: a thread-per-connection server has no upper bound on threads in this version. A thousand simultaneous connections means a thousand threads, each with a stack (typically around 1 MB by default, though configurable with -Xss). That is workable at small scale and problematic beyond it, which is why the next sections revisit the model.

Step 3: Build the client

The client connects, writes a request, reads a response, and can repeat.

The flush() call matters. Without it, the buffered writer may hold the request in memory and the server will sit waiting for data that never arrives — a classic deadlock that looks like a hung server but is actually a client-side buffering bug.

Step 4: Run both sides and verify success

Start the server in one terminal, then the client in another. A passing run prints a timestamp for TIME, hello world for the echo, and ERROR unknown command for the bogus request.

To check success independently of your client code, use a raw tool. On Unix-like systems, nc 127.0.0.1 5000 (or ncat) lets you type a request line and see the response. That isolates protocol problems from client-code problems: if nc works and your Java client does not, the bug is in the client; if nc also fails, look at the server.

Failure modes to check in order, starting with the most reversible:

Connection refused. Nothing is listening on that port, or the server crashed, or you are connecting to a different address family (IPv4 vs. IPv6) than the server bound to. Check the server's printed listening address. Connection accepted but no response. Almost always a missing flush() on the client, or the server reading a different delimiter than the client sends. Garbled text. Encoding mismatch — confirm both sides construct readers and writers with StandardCharsets.UTF_8. Server hangs after one client. You are running a single-threaded accept-and-handle loop; the handler is blocking the accept loop. This is the cue to move to the threaded version above.

Once nc and the Java client both succeed, the basic architecture is verified and you can extend it.

Step 5: Scale the server beyond thread-per-connection

Thread-per-connection is fine for learning and for modest loads, but two limits appear. First, thread counts. Second, no isolation: one misbehaving client that opens connections and never sends data ties up a thread indefinitely.

Two straightforward upgrades:

Bounded thread pool. Replace new Thread(...) with an ExecutorService sized to a fixed number of threads. When the pool is saturated, new connections queue. This caps resource usage but introduces a latency risk: a burst of slow clients can starve fast ones. Set the queue length and rejection policy deliberately rather than accepting the defaults.

Virtual threads. On JDK 21 or later, Executors.newVirtualThreadPerTaskExecutor() gives you thread-per-connection semantics with far cheaper threads, so a server can hold many more idle connections. The blocking I/O style stays the same — no rewrite into callbacks. The caveat: virtual threads help with I/O-bound concurrency, not CPU-bound work, and pinning can occur inside synchronized blocks that block on I/O in some JDK versions, so measure under realistic load rather than assuming.

For very high connection counts with small messages, a non-blocking design with java.nio channels and a selector avoids one thread per connection entirely. It is substantially harder to write correctly. Do not reach for it unless measurements show the simpler model failing.

A rough capacity estimate makes the trade-off concrete. Suppose each thread reserves about 1 MB of stack by default. Five hundred concurrent connections at 1 MB each is roughly 500 MB of stack space, which may or may not be acceptable depending on your heap and container limits. With virtual threads or a pool of 50 platform threads, that pressure drops sharply — at the cost of queuing when all 50 are busy.

Step 6: Add HTTP when you need standard semantics

Raw TCP is right when you control both ends and want minimal overhead. HTTP is right when browsers, proxies, load balancers, or third-party clients must talk to your server, or when you want status codes and caching semantics without inventing them.

Java ships a lightweight HTTP server in com.sun.net.httpserver. It is documented as a simple server suitable for embedded use, not a full-featured production web server, so treat it as a teaching and prototyping tool. A minimal handler:

On the client side, java.net.http.HttpClient (finalized in Java 11) handles connection pooling, redirects, and timeouts. A request to the above server is a few lines and, unlike the raw socket approach, you get a status code and headers without parsing them yourself; HttpClient also supports asynchronous requests via sendAsync.

The trade-off is honest: HTTP adds request/response ceremony and a header overhead per message that a line-based socket protocol avoids. For a game loop or a high-frequency sensor feed where both ends are yours, raw TCP remains the leaner choice. For anything a browser or standard tooling must reach, HTTP wins on compatibility.

Step 7: Make it robust with timeouts, limits, and clean failure

The minimal server has three production hazards.

No read timeout. A client that connects and never sends data holds the handler thread forever. Set socket.setSoTimeout(...) on accepted sockets so blocked reads eventually throw SocketTimeoutException and the handler can close. Choose a value tied to your expected interaction: seconds for chatty protocols, longer for infrequent batch jobs. For HTTP, set timeouts on the HttpClient (connect timeout and request timeout) rather than relying on defaults.

No message size limit. BufferedReader.readLine() will happily grow a buffer until memory runs out if a client sends an endless line. Enforce a maximum length: read with a bounded buffer and reject requests over the limit, closing the connection with an error. Length-prefixed framing makes this easier because the server can read the declared length and reject it before allocating.

Unhandled exceptions silently killing connections. The handler catches IOException above, but a RuntimeException in process() would propagate and close the socket with no log. Catch broadly inside the handler, log the error, and return a defined error response so clients see a message rather than a reset connection.

Also decide what a graceful shutdown looks like. On a signal, stop accepting new connections, let in-flight requests finish up to a deadline, then close. Java's shutdown hooks (Runtime.getRuntime().addShutdownHook) are the conventional place to trigger this, though they run only for orderly termination.

Step 8: Separate the protocol layer from the transport

Once the toy version works, the next refactor matters more than any feature: put message parsing and business logic in classes that know nothing about sockets. A RequestProcessor that takes a request string and returns a response string can be tested with plain unit tests, no network needed. The socket handler becomes a thin adapter that reads a line, calls the processor, writes the result.

This separation pays off when you later add a second transport — say HTTP alongside raw TCP — because the logic is shared and only the adapters differ. It also makes the failure modes easier to localize: a parsing bug fails a unit test, not an integration run.

The same principle applies to the client. Wrap the socket in a small class exposing sendRequest(String) -> String, so the rest of the client code does not depend on sockets and can be tested against a fake implementation.

Where this design breaks and what to do next

The simple architecture has known ceilings, and naming them prevents surprise.

Many idle connections. Thread-per-connection, even with a pool, wastes resources on clients that connect and wait. Virtual threads or non-blocking I/O help; a heartbeat protocol that closes dead connections helps more. Large payloads. Line-delimited text protocols choke on binary data or multi-megabyte messages. Switch to length-prefixed framing or HTTP with streaming bodies. Multiple server instances. A single process is a single point of failure. Running several behind a load balancer requires the protocol to be stateless per request, or shared session state in an external store. Security. Raw sockets have no authentication or encryption. TLS via SSLServerSocket and SSLSocket adds encryption, but authentication and authorization remain your design problem. For HTTP, terminate TLS at a reverse proxy or use HttpsServer. Serialization drift. If client and server versions deploy separately, a changed message format breaks the other side. Version your protocol explicitly, and make the server tolerant of unknown fields.

None of these require abandoning the architecture — they require deciding which constraints apply to your system and choosing the transport and concurrency model accordingly, which is exactly the decision the first step forced.

A compact comparison of the three common transports

Criterion Raw TCP sockets Built-in HTTP server Framework (e.g., a servlet container or modern web framework)
Setup effort Low — standard library only Low — com.sun.net.httpserver Higher — dependencies, configuration
Client compatibility Custom client required Any HTTP client, browsers, curl Same as HTTP
Message overhead Minimal Headers and status line per request Similar to HTTP, plus framework overhead
Concurrency handling You implement it You supply an executor Built in
Production suitability Depends on your implementation Prototyping and embedded use Designed for it
Best fit Both ends under your control, low latency Internal tools, simple services, learning Public-facing services with routing, auth, observability

The comparison is not a ranking. A raw TCP server with careful timeouts and framing can be production-grade for a narrow use case, and an HTTP framework can be overkill for a two-machine internal tool.

FAQ

Can I use Java's SocketChannel instead of Socket? Yes. SocketChannel from java.nio supports non-blocking mode and selectors, which is the path to handling many connections on few threads. It is more code and more error-prone; use it when measurements show the blocking model is the bottleneck.

Do I need a separate thread for reading and writing on the client? Only if the client must send while waiting for a response, such as in a chat application where either side can initiate. For strict request-then-response interactions, a single thread is simpler and avoids synchronization bugs.

How do I test the server without a real client? Connect with nc or curl (for HTTP), or write a JUnit test that starts the server on an ephemeral port, connects a socket, and asserts on the response. Ephemeral ports — pass 0 as the port and read getLocalPort() — avoid conflicts in test runs.

Is the built-in HTTP server safe to expose to the internet? The JDK documentation describes it as a simple server for embedded use, not a full-featured production server. For public-facing services, use a framework or a dedicated server and place TLS and access controls in front of it.