如何在程序正常关闭或崩溃时确保我的程序关闭套接字?

时间:2012-03-12 04:16:39

标签: java sockets

以下是代码:

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();
    }
}

SocketWorker只是一个套接字,监听端口2012,而MyIOConsole将接受用户命令,

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);
    }

}

但是当Socket得到异常时,即使我抓住它们,代码

        mio.applicationQuit();

继续跑。我不希望这样,我只是想当用户关闭或崩溃应用程序时,套接字将关闭并退出。我该如何解决?

1 个答案:

答案 0 :(得分:2)

添加以下内容。当JVM退出时,将调用run方法。

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