Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

java - How to close ServerSocket connection when catching IOException?

Sorry for question, but I'm totally noob in Java. What is the best practice to execute ServerSocket.close() when caught IOException from ServerSocket? According to docs, ServerSocket.close() throws IOException and compiler asks us to catch it. What is the proper way to close connection on IOException?

try {
    server = new ServerSocket(this.getServerPort());
    while(true) {
        socket = server.accept();
        new Handler( socket );
    }
} catch (IOException e) {
    if (server != null && !server.isClosed()) {
        server.close(); //compiler do not allow me to do because I should catch IOExceoption from this method also...
    }
}

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are going to close the ServerSocket outside of the try{}catch{} anyways, you may as well put it in a finally{}

try {
    server = new ServerSocket(this.getServerPort());
    while(true) {
        socket = server.accept();
        new Handler( socket );
    }
} catch (IOException e) {
    // Do whatever you need to do here, like maybe deal with "socket"?
}
finally {
    try {  
        server.close();
    } catch(Exception e) {
        // If you really want to know why you can't close the ServerSocket, like whether it's null or not
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...