How to close ServerSocket connection when catching IOException?

后端 未结 4 999
爱一瞬间的悲伤
爱一瞬间的悲伤 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 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
        }
    }
    
    0 讨论(0)
  • 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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-21 08:11

    You can close the resources in the finally block,

    http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html

     } finally {
          try {
            socket.close();
          } catch(IOException e) {
             e.printStackTrace(); 
          }
    }
    
    0 讨论(0)
  • 2020-12-21 08:13

    In Java SE 7 or later you can use try-with-resources statement, ServerSocket implements java.io.Closeable, so you don't need to explicitly #close() the socket when used in this way.

    try (ServerSocket server = new ServerSocket(this.getServerPort())) {
        while(true) {
            socket = server.accept();
            new Handler( socket );
        }
    } catch (IOException e) {
        // It's already closed, just print the exception
        System.out.println(e);
    }
    
    0 讨论(0)
提交回复
热议问题