Search code examples
javasocketsserversocket

In this Java socket code, does this infinite loop get terminated by the socket closing?


This is a basic Java Server ( source ) , but i don't quite get it because I'm curious about the while(true) part , when does it ever terminate?

public static void main(String[] args) throws IOException {
    ServerSocket listener = new ServerSocket(9090);
    try {
        while (true) {
            Socket socket = listener.accept();
            try {
                PrintWriter out =
                    new PrintWriter(socket.getOutputStream(), true);
                out.println(new Date().toString());
            } finally {
                socket.close();
            }
        }
    }
    finally {
        listener.close();
    }
}

How will we ever reach the last part, which is

finally {
        listener.close();

Or is it just standard networking code, to have the while(true) ?


Solution

  • If an exception is thrown, the loop will be broken out of.

    IO-related code in Java, when it fails, will almost always throw an exception which indicates why it failed. You can look up the method being called in http://docs.oracle.com/javase/6/docs/api/java/io/package-summary.html and see what exceptions it can throw, for example.

    while(true) is a common idiom for daemons, servers and so on 's main loops that you expect to never stop running, or that you stop in the form of throwing an exception.