Skip to content
Tutorials Center
My learning

Topics

Lesson 141 of 201 ยท Networking

TCP Sockets

Learn Java TCP socket programming - ServerSocket and Socket, an echo server and client, reading and writing over streams, timeouts, many clients and closing properly.

Every web page you load, every database query your app sends and every chat message you type travels over a TCP connection. In Java, the classic way to open one is the socket API in java.net: a ServerSocket waits for connections on a port, and a Socket is one end of an established connection. Once connected, both sides simply get an InputStream and an OutputStream, so everything you learned in Byte and Character Streams applies directly.

Higher-level tools such as the HTTP client, JDBC drivers and web servers are all built on top of sockets. Knowing how sockets behave (how they block, how data is framed, how connections end) makes you much better at debugging those tools too. In this lesson you'll build an echo server and client, design a small text protocol, serve several clients at once and handle timeouts and closed connections. Because our sandbox has no internet access, every example runs the server and the client in the same program, talking over the loopback address 127.0.0.1, exactly as Networking Basics described.

How a TCP conversation works

A TCP conversation always has two roles:

  1. The server creates a ServerSocket bound to a port and calls accept(). That call blocks until a client connects, then returns a brand-new Socket for that one client.
  2. The client creates a Socket with the server's address and port. The constructor performs the TCP handshake and returns once the connection is open (or throws if nobody is listening).
  3. Both sides read and write bytes through getInputStream() and getOutputStream(). TCP delivers the bytes reliably and in order.
  4. Either side calls close(). The other side's reads then return end-of-stream (-1, or null from readLine()).

The key mental model: TCP is a byte stream, not a message service. If the client writes "hello" and then "world", the server might receive "helloworld" in one read, or "hel" and "loworld" in two. You decide where one message ends and the next begins, usually with line breaks or a length prefix. That decision is your protocol.

Java
// Server side (simplified)
try (ServerSocket server = new ServerSocket(5000)) {
    Socket client = server.accept();          // waits for one client
    InputStream in = client.getInputStream();
    OutputStream out = client.getOutputStream();
    // ... talk to this client ...
}

// Client side (simplified)
try (Socket socket = new Socket("localhost", 5000)) {
    OutputStream out = socket.getOutputStream();
    InputStream in = socket.getInputStream();
    // ... talk to the server ...
}

An echo server and client in one program

The first full example starts a server on a background thread and connects to it from main. A few details are worth noticing before you run it:

  • new ServerSocket(0, 50, InetAddress.getLoopbackAddress()) asks the operating system for any free port (port 0), with a backlog of 50 pending connections, listening only on the loopback interface. Real servers use a fixed port, but port 0 avoids "address already in use" clashes in tests and demos.
  • Text needs a charset, so the raw streams are wrapped in InputStreamReader/OutputStreamWriter with UTF-8, then in BufferedReader and PrintWriter.
  • new PrintWriter(writer, true) turns on auto-flush for println. Without flushing, your line might sit in a buffer while both sides wait for each other forever.
Java Echo server and client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows the full life of a connection: connect, three request/response round trips, then the server's readLine() returns null because the client closed its socket. Compact source files import all of java.base automatically, which includes java.net and java.io; in a normal class you'd add import java.net.*; and import java.io.*;.

Socket and ServerSocket implement AutoCloseable, so use try-with-resources. Closing any stream obtained from a socket closes the whole socket, and closing the socket closes both streams.

Designing a simple text protocol

An echo server is a good warm-up, but real servers understand commands. A line-based protocol is the easiest to build and debug: each request is one line, each response is one line. Many famous protocols (SMTP, Redis, early HTTP) work this way.

The next example implements a tiny in-memory key-value store with three commands: SET key value, GET key and QUIT. Notice how the server answers every request with exactly one line, including errors. A predictable shape like that keeps the client simple: send one line, read one line.

Java A key-value server with a line protocol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

After QUIT the server leaves its loop and its try-with-resources closes the socket, so the client's next readLine() returns null. That's how a client learns that the other side has gone away.

Text lines or length prefixes?

Line-based protocols are easy to read, but a value can't contain a newline unless you escape it. Binary protocols usually send a length prefix first: "the next message is 37 bytes." DataOutputStream.writeUTF does exactly that (a 2-byte length followed by the bytes, limited to 65,535 bytes), and DataInputStream.readUTF reads one whole message back no matter how TCP split it. For larger messages, write an int length with writeInt and then the bytes, and read them back with readInt and readFully.

Java
// Sender
var out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
byte[] payload = message.getBytes(StandardCharsets.UTF_8);
out.writeInt(payload.length);
out.write(payload);
out.flush();                       // buffered streams must be flushed

// Receiver
var in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte[] buffer = new byte[in.readInt()];
in.readFully(buffer);              // loops until every byte has arrived
String message = new String(buffer, StandardCharsets.UTF_8);

Never trust a length prefix blindly: a buggy or malicious client could send 2,000,000,000 and make your server allocate gigabytes. Check it against a sensible maximum first.

Serving many clients

The servers above handle one client and then stop. A real server loops forever around accept() and hands each connection to its own thread, so a slow client can't block everyone else. Before Java 21 you'd use a fixed thread pool; today virtual threads are the natural fit, because a blocked socket read parks a virtual thread cheaply instead of tying up an operating-system thread.

The example below starts a server that accepts connections in a loop and serves each one on a virtual thread. Five clients connect at the same time, each sends its name, and the server replies with a greeting and a running count. Closing the ServerSocket at the end makes the blocked accept() throw a SocketException, which is the standard way to stop an accept loop.

Java One virtual thread per client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The client numbers depend on which connection the server handled first, so they can change from run to run; the program hides them to keep the output stable. The total is always 5 because AtomicInteger counts safely across threads (see Atomic Variables). Here the streams use the default charset, which has been UTF-8 since Java 18.

A thread per connection is only safe if every thread eventually finishes. A client that connects and never sends anything keeps its thread waiting forever. Production servers always set read timeouts and limit the number of open connections.

Timeouts and failures

Networks fail in ways local code never does. Every socket program should be ready for these situations:

Situation What Java does
Nothing listens on the port new Socket(...) throws ConnectException: Connection refused
The host doesn't answer (firewall, dead machine) connect can hang for a long time; use socket.connect(address, timeoutMillis)
The peer is connected but silent read blocks forever, unless you call setSoTimeout(ms), which makes reads throw SocketTimeoutException
The peer closed the connection normally read() returns -1, readLine() returns null
The peer vanished abruptly reads or writes throw SocketException (for example "Connection reset")

The next example triggers three of these deliberately. It finds a free port and closes it again so that a connection attempt is refused, it connects to a server that never replies with a 300 ms read timeout, and it shows that a SocketTimeoutException doesn't close the socket: you can decide whether to retry or give up.

Java Refused connections and read timeouts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The exact text of the refused-connection message comes from the operating system, but it usually starts with "Connection refused" (our server prints Connection refused (connect failed)). Always set both a connect timeout and a read timeout in client code that talks to other machines; the defaults wait forever (or for minutes, depending on the OS).

Closing connections properly

Closing is part of the protocol, not an afterthought:

  • Close in a finally or try-with-resources. Each open socket holds a file descriptor; a server that leaks them eventually fails with "Too many open files".
  • Flush before closing. A buffered writer that is closed flushes itself, but if you close the socket directly (not the writer), buffered data can be lost.
  • Half-close when you're done sending. socket.shutdownOutput() tells the peer "no more data from me" (it sees end-of-stream) while you can still read its reply. This is handy for "send the whole request, then read the whole response" protocols.
  • isClosed() and isConnected() only describe your end. isConnected() stays true after the peer disconnects. The only reliable way to detect a closed peer is a read returning -1 or a write failing.
Java
try (var socket = new Socket(host, port)) {
    socket.getOutputStream().write(request);
    socket.shutdownOutput();                           // peer's read sees end-of-stream
    byte[] response = socket.getInputStream().readAllBytes();  // read until the peer closes
}

Beyond the basics

The blocking Socket API, combined with virtual threads, is enough for most applications. A few related tools are worth knowing by name:

  • TLS: SSLSocketFactory.getDefault().createSocket(host, 443) gives an encrypted socket with the same stream API. Use it (or a higher-level client) for anything that crosses a network you don't control.
  • NIO channels: java.nio.channels.SocketChannel and Selector let one thread watch thousands of non-blocking connections. Frameworks like Netty use them; with virtual threads, most application code no longer needs to.
  • Socket options: setTcpNoDelay(true) disables Nagle's algorithm for chatty, latency-sensitive protocols; setKeepAlive(true) asks the OS to probe idle connections; setReuseAddress(true) on a ServerSocket lets a restarted server bind to a port still in the TIME_WAIT state. NIO channels expose the same settings as typed StandardSocketOptions constants (see UDP).
  • Higher-level protocols: for HTTP, use the Java HTTP Client instead of writing HTTP over a raw socket.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client writes "abc" and then "def" to a socket with two separate write calls. What can the server's reads return?

    TCP is an ordered byte stream with no message boundaries. Bytes always arrive in order, but how they are grouped into reads is up to the network and OS, so protocols use delimiters or length prefixes.
  2. 2. The server calls in.readLine() and it returns null. What does that mean?

    readLine returns null only at end of stream, which happens when the peer closes the connection or shuts down its output. An empty line comes back as "" and a timeout throws SocketTimeoutException.
  3. 3. A client uses new PrintWriter(socket.getOutputStream()) (no auto-flush), calls println("PING") and then waits on readLine(). The server never answers. What is the most likely cause?

    Without flushing, the data stays in a local buffer. Both sides then wait for each other. Use new PrintWriter(stream, true) or call flush() after each message.
  4. 4. What does socket.setSoTimeout(500) do?

    SO_TIMEOUT applies to reads (and accept on a ServerSocket). The socket stays usable after the exception. Connection timeouts are set with connect(address, timeout).
  5. 5. Why do the examples create new ServerSocket(0, ...)?

    Binding to port 0 lets the operating system choose an unused ephemeral port. That's ideal for tests and demos; real servers listen on a well-known, fixed port.

Summary

  • A ServerSocket listens on a port; accept() blocks and returns a new Socket per client. A client connects with new Socket(host, port) or connect(address, timeout).
  • After connecting, both sides use ordinary streams. Wrap them with a charset (InputStreamReader, OutputStreamWriter) for text, and flush, or use auto-flush, after each message.
  • TCP is a byte stream without message boundaries, so design a protocol: one command per line, or a length prefix with DataInputStream/DataOutputStream.
  • Serve many clients by looping on accept() and handling each connection on its own (virtual) thread; close the ServerSocket to stop the loop.
  • Expect failures: ConnectException, SocketTimeoutException (set setSoTimeout), SocketException and end-of-stream (-1/null) when the peer closes.
  • Close sockets with try-with-resources, use shutdownOutput() to half-close, and remember that isConnected() says nothing about the peer.

Next: UDP with DatagramSocket, where you'll send self-contained packets without a connection and see when that's the better choice.