套接字连接不会超时
我试图在客户端尝试连接到服务器时设置超时,如果服务器关闭,连接将等待 10 秒,然后抛出超时异常。 就我而言,下面的代码无需等待就抛出 IOException,我真的不明白!
public boolean establishConnection()
{
System.out.println ("Connecting to " +
this.getServerHostname() + " au port " + this.getServerPort()+ " ...");
try {
SocketAddress sockaddr= new InetSocketAddress(_serverHostname, _serverPort);
_echoSocket = new Socket();
_echoSocket.connect(sockaddr,10000);
return _echoSocket.isConnected();
} catch (UnknownHostException e) {
System.err.println("Unknown Host: " + this.getServerHostname());
return false;
} catch (SocketTimeoutException e) {
System.err.println("Timeout");
return false;
} catch (IOException e) {
System.err.println("IOException : " +
this.getServerHostname() + ":" + this.getServerPort());
return false;
}
}
I'am trying to set a timeout when a client try to connect to a server, if the server is down, the connection will wait 10 sec befor throwing the timeout exception.
In my case the code bellow throw the IOException without waiting, I really don't get it !
public boolean establishConnection()
{
System.out.println ("Connecting to " +
this.getServerHostname() + " au port " + this.getServerPort()+ " ...");
try {
SocketAddress sockaddr= new InetSocketAddress(_serverHostname, _serverPort);
_echoSocket = new Socket();
_echoSocket.connect(sockaddr,10000);
return _echoSocket.isConnected();
} catch (UnknownHostException e) {
System.err.println("Unknown Host: " + this.getServerHostname());
return false;
} catch (SocketTimeoutException e) {
System.err.println("Timeout");
return false;
} catch (IOException e) {
System.err.println("IOException : " +
this.getServerHostname() + ":" + this.getServerPort());
return false;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的连接请求未得到答复,您只会遇到超时。如果服务器立即拒绝它,或者服务器不存在,您将立即收到异常。
You'll only get a timeout if your connection request is not answered. If the server immediately rejects it, or if the server doesn't exist, you'll get an exception immediately.
但这是您想要实现的目标吗?
如果您的意图是,万一服务器暂时宕机,则 10 秒后重试,那么您的做法是错误的。
您应该尝试连接到服务器,如果由于服务器关闭而出现异常,您可以
睡眠
10 秒,然后再次尝试请求。否则欧内斯特的答案是正确的
But is this what you want to achieve?
If your intention is, in case the server is temporarily down, then try again after 10 sec then your approach is wrong.
You should try to do a connection to the server and if you get an exception because the server is down, you can
sleep
for 10 seconds and try the request again.Otherwise Ernest's answer is correct