Socket Client With Connect Timeout

Probe a TCP service with Socket connect timeout and setSoTimeout so a dead peer cannot hang the caller, using a local ServerSocket as the responder.

JavaResilience

Code

snippet
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class SocketTimeoutProbe {

    public static void main(String[] args) throws IOException, InterruptedException {
        // Throwaway server: bind port 0 so the system picks a free port; the child thread answers once
        try (ServerSocket server = new ServerSocket(0)) {
            Thread responder = Thread.ofPlatform().start(() -> {
                try (Socket conn = server.accept();
                     PrintWriter out = new PrintWriter(conn.getOutputStream(), true,
                             StandardCharsets.UTF_8)) {
                    out.println("pong");
                } catch (IOException ignored) {
                    // If the peer times out and disconnects, the server exits quietly
                }
            });

            try (Socket client = new Socket()) {
                // Connect timeout: a failed handshake within 500ms throws, so the probe never hangs
                client.connect(new InetSocketAddress("localhost", server.getLocalPort()), 500);
                client.setSoTimeout(500); // reads must also finish within 500ms
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
                System.out.println("reply: " + in.readLine());
            }
            responder.join();
            System.out.println("probed port " + server.getLocalPort());
        }
    }
}

How the snippet works

The moving parts are the class SocketTimeoutProbe.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The demo output is labeled (reply:, probed port), so every printed line maps back to its originating operation.

Key statements

Thread responder = Thread.ofPlatform().start(() -> {
try (Socket conn = server.accept();
PrintWriter out = new PrintWriter(conn.getOutputStream(), true,
StandardCharsets.UTF_8)) {
out.println("pong");
} catch (IOException ignored) {
// If the peer times out and disconnects, the server exits quietly
}
});

Interactive Tools for This Topic

FAQ

What does Socket Client With Connect Timeout print when run?
The script runs standalone; its 2 labeled outputs include `reply:`, `probed port`.