views:

347

answers:

2

Having a console application, a server accepting several connections from clients, is it possible to have a listener or an event on a closing application? I want, in this event, tell all connected clients to gently disconnect before the application really closes itself.

Any solution? Thank you!

A: 

If by closing application you mean the operating system killing the server process?

In that situation there is no way for the server to know it is being killed. It will drop the existing connections.

If by closing application you provide a method for the sys admin to manually close the server ( probably by typing "exit" at server console ). Then the closing event would be a custom event, and you would have to code the listeners and notify to everyone the server is shutting down. In this scenario it is posible.

Try adding more details about how your server is built or how it works.

OscarRyz
+3  A: 

You want to use a shutdown hook:

Runtime.getRuntime().addShutdownHook(theHookThread);

So the thread will be run when the JVM shuts down, see here for details.

Tom
With a quick search, I have found this article (http://www.onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html?page=1), and it's exactly what I was looking for. Thanl you!
elbaid