套接字连接不会超时

发布于 2024-11-08 19:42:03 字数 924 浏览 1 评论 0原文

我试图在客户端尝试连接到服务器时设置超时,如果服务器关闭,连接将等待 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

诗化ㄋ丶相逢 2024-11-15 19:42:03

如果您的连接请求未得到答复,您只会遇到超时。如果服务器立即拒绝它,或者服务器不存在,您将立即收到异常。

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.

仅此而已 2024-11-15 19:42:03

但这是您想要实现的目标吗?
如果您的意图是,万一服务器暂时宕机,则 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文