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.
Code
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
CIDR to IP ListExpand an IPv4 CIDR block into its individual addresses, showing network, broadcast, total count, and a bounded list you can copy.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.IPv6 CompressorCompress an IPv6 address per RFC 5952 and show its fully expanded form, validating every hextet.MAC Address FormatterNormalize a MAC address from any separator style into colon, hyphen, Cisco dotted, and plain forms, with 12-hex-digit validation and case control.
FAQ
- What does Socket Client With Connect Timeout print when run?
- The script runs standalone; its 2 labeled outputs include `reply:`, `probed port`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.