简体   繁体   中英

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

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();
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM