How to close ServerSocket connection when catching IOException?

后端 未结 4 1000
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  -上瘾入骨i
    2020-12-21 07:56

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

提交回复
热议问题