本文介绍了如何在捕获IOException时关闭ServerSocket连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

很抱歉问题,但我在Java中完全是noob。从 ServerSocket IOException 时执行 ServerSocket.close()的最佳做法是什么? / code>?根据文档, ServerSocket.close()抛出 IOException 并且编译器要求我们捕获它。在 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...
    }
}

谢谢!

推荐答案

这在Java中很难看。我讨厌它,但这是你应该这样做的方式:将它包装成另一个try-catch:

That's ugly in Java. I hate it, but this is the way you should do it: Wrapping it into another try-catch:

try {
    server = new ServerSocket(this.getServerPort());
    while(true) {
        socket = server.accept();
        new Handler( socket );
    }
} catch (IOException e) {
    if (server != null && !server.isClosed()) {
        try {
            server.close();
        } catch (IOException e)
        {
            e.printStackTrace(System.err);
        }
    }
}

这篇关于如何在捕获IOException时关闭ServerSocket连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 11:13