开发者

How do I catch 'connection refused' exception in Java?

开发者 https://www.devze.com 2023-03-23 21:32 出处:网络
I want to know how I can catch a \'connection refused\' exception in Java when I am using socket. (which would happen when server is down or not responding.)

I want to know how I can catch a 'connection refused' exception in Java when I am using socket. (which would happen when server is down or not responding.)

Below is how I have implemented so far.

    try {
        sockfd = new Socket(host.getHostName(),heart_port);
        sockfd.setReuseAddress(true);
        BufferedReader message = new BufferedReader(new InputStreamReader ( sockfd.getInputStream() ) );
        message.close();
        sockfd.close();
    }开发者_运维知识库 catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


Add ConnectException before IOException

catch (ConnectException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消