How to close ServerSocket connection when catching IOException?

后端 未结 4 1003
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 07:10

Sorry for question, but I\'m totally noob in Java. What is the best practice to execute ServerSocket.close() when caught IOException from Ser

4条回答
  •  醉酒成梦
    2020-12-21 08:06

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

提交回复
热议问题