← 中文资源

简体中文版本

带连接超时的 Socket 客户端探测

用 connect(addr, timeout) 与 setSoTimeout 给 TCP 探测设上限:连接与读取两段都不许超过预算,死对端不会拖住调用方;本例用本地 ServerSocket 充当被探测服务,行为可复现。

阅读英文原文

实现说明

带连接超时的 Socket 客户端探测可以归结为类 SocketTimeoutProbe。 try-with-resources 保证即使方法体抛出,声明的资源也会被关闭。

使用要点

  • 跑完文件,输出里会留下标记——reply:、probed port。

常见问题

运行「带连接超时的 Socket 客户端探测」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 reply:、probed port 标签标明各步骤。

核心语句

client.connect(new InetSocketAddress("localhost", server.getLocalPort()), 500);

代码示例

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());
        }
    }
}