Recently I have been flicking through a Java book on games programming that I was fortunate enough to pick up for free on my trip to JavaOne (thank you nice people on the O’Reilly stand, and Andrew from StrongAuth for saving it for me!). While slightly out of date (it was written for Java 1.4 or 5) it still has many interesting explanations and examples of useful code and techniques for making games.
One part that interests me and caused me to write this blog article, is the networking section of the book. Within this section it shows off how to use Sockets to create a basic Score Server for a game. It’s very good at explaining it with the code divided up between explanations of what it does but it contains within it a certain statement I was taught to avoid when learning to program. That statement is within the title of this blog post; while(true).
Although in the given situation you may want to have your server loop running virtually forever I am still a little dubious that using a while(true) loop is really the necessary way of handling, and looking into the JavaDocs of the ServerSocket class there is a function called isClosed() that would be better suited to be the task and allow the server socket to be closed when needed and exit cleanly.
However, this may just be a coding practice that has been banged into my head from College and University, so what are your opinions on it? Is it a bad practice? Or is it acceptable given there is a breaking statement somewhere in the loop (in this example there was none)?
I made a quick Java Program showing code based off of the example from the book, including the while(true) loop. You can see it here on my github.
Also, sorry if the title confuses or offends anyone, I thought it was quite clever…