简体   繁体   中英

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) ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM