DNB5brims
DNB5brims

Reputation: 30568

How do I ensure my program closes the socket whenever it closes normally or crashes?

Here is the code:

public static void main(String[] args) {
    SocketWorker worker = null;
    MyIOConsole  mio = null;

    try {
        portNumber = 2012;

        worker = new SocketWorker();    
        worker.assignPort(portNumber);

        mio = new MyIOConsole();
        mio.assignObject(worker);

        Thread b = new Thread(mio); 
        b.start();

        worker.run();

    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        mio.applicationQuit();
    }
}

The SocketWorker is simply a socket, listening the port 2012, and the MyIOConsole, will accept user command,

public class MyConsoleIO implements Runnable {

    SocketWorker o;
    static BufferedReader reader;

    public void assignObject(Object o) {

        reader = new BufferedReader(new InputStreamReader(System.in));

        this.o = (SocketWorker) o;

    }

    @Override
    public void run() {
        String inputString = null;

        System.out.println("Press 'q' to kill to program");
        try {
            inputString = reader.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (inputString.equalsIgnoreCase("q")) {
            this.applicationQuit();
        }
    }

    public void applicationQuit(){
        this.o.stopWorking();
        System.exit(0);
    }

}

But when the Socket got the exception, even I catch them, the code

        mio.applicationQuit();

keep run. I don't want that, I just want when the user close or crashed the application, the socket will close and quit. How can I solve it?

Upvotes: 0

Views: 113

Answers (1)

Java42
Java42

Reputation: 7706

Add the following. The run method will be called as the JVM is exiting.

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run(){
        // cleanup code before JVM exit goes here.
    }
});

Upvotes: 2

Related Questions