Java:如何使用 "try with resources" 设置套接字超时

Java: How to set a socket timeout with a "try with resources"

我想设置套接字连接超时。我知道我可以使用连接方法设置它,但这是我的代码:

try(Socket socket = new Socket(InetAddress.getByName(ip), port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true)){
try(Socket socket = new Socket(InetAddress.getByName(ip), port)) {
    socket.connect(adress, timeout);
} catch (Throwable t) {
    handleException(t);
}

从你的问题中并不清楚你卡在哪里,但你可以继续使用 connect 方法:

int timeout = 25000;
try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress("abc", 123), timeout);
    try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
         PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true)) {

    }
}