gpt4 book ai didi

java - Java:如何使用 “try with resources”设置套接字超时

转载 作者:行者123 更新时间:2023-12-03 11:57:50 26 4
gpt4 key购买 nike

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

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)){

最佳答案

从您的问题中并不清楚您被卡在哪里,但是您可以继续使用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)) {

}
}

关于java - Java:如何使用 “try with resources”设置套接字超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com