running code when the program closes

I have a server that has a main loop listed below:

while (listening)

{

new ServerThread(serverSocket.accept()).start();

}

The only way I have to stop the server is to manually close it, because the serversocket.accept() method blocks until a connection is made. I would like to be able to execute some code before I close the server, such as saving things to a file. However, I can't do this because I'm closing the program manually. I came up with a solution where the program has a keyListener that waits for a key to be pressed and then prompts the user if he wants to close the server. However, this would only work if there was some way to check for a client every iteration of the loop, but not block. The other thing I had in mind was putting the file writing code into some place that java always runs before it closes a program.

I'm looking for someone to explain how I could either check for a client without blocking, or make some code run every time I close the program. If the above explanation was confusing, I'd be happy to clarify.

[1212 byte] By [Japhetha] at [2007-11-27 3:10:45]
# 1
Runtime.getRuntime().addShutdownHook to execute code at shutdown.ServerSocket has a close method that should cause the accept method to throw an exception.
robtafta at 2007-7-12 8:13:10 > top of Java-index,Other Topics,Java Game Development...
# 2
Thanks. I made a separate thread for the loop that accepts connections, so I can check for input and close the socket in the main class. I haven't done anything with addShutdownHook() yet, but it shouldn't be too compicated.
Japhetha at 2007-7-12 8:13:10 > top of Java-index,Other Topics,Java Game Development...
# 3

The obvious way to do this nicely would be to have a simple client program which connects to that socket and sends a shutdown message. Obviously you have to think about how to do this securely, to avoid potential for denial of service, but it does avoid the problems of needing a console.

One other idea would be to use native code to listen for process signals. This is OS-dependent, but relatively clean and in keeping with the way *nix systems tend to work.

YAT_Archivista at 2007-7-12 8:13:10 > top of Java-index,Other Topics,Java Game Development...