如何安全地停止此Java服务器程序?

时间:2016-06-15 18:48:39

标签: java sockets server

我想通过终端在我的ubuntu计算机上运行一个java服务器程序但问题是,一旦我启动程序,我就无法阻止它(程序在终端中运行并等待客户端)。

这是我的代码:

import java.net.*; 
import java.io.*; 

public class EchoServer2 extends Thread {
    protected Socket clientSocket;

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(2000);
            System.out.println("Connection Socket Created");
            try {
                while (true) {
                    System.out.println("Waiting for Connection");
                    new EchoServer2(serverSocket.accept());
                }
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
            }
        } catch (IOException e) {
            System.err.println("Could not listen on port: 2000.");
            System.exit(1);
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                System.err.println("Could not close port: 2000.");
                System.exit(1);
            }
        }
    }

    private EchoServer2(Socket clientSoc) {
        clientSocket = clientSoc;
        start();
    }

    public void run() {
        System.out.println("New Communication Thread Started");

        try {
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
                    true);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));

            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                System.out.println("Server: " + inputLine);
                out.println(inputLine);

                if (inputLine.equals("Bye."))
                    break;
            }

            out.close();
            in.close();
            clientSocket.close();
        } catch (IOException e) {
            System.err.println("Problem with Communication Server");
            System.exit(1);
        }
    }
}

我知道我可以杀死这个过程,但我不想强行停止这个程序。我想知道:如何安全地停止程序?我怎样才能在我的代码中实现它?

3 个答案:

答案 0 :(得分:1)

您可以点击 $.getJSON(url, function (data) { $("#products").remove(); var html = '<div id="products" class="row list-group">'; for (var i = 0;i<data.length;i++) { html += '<div class="item ' + $("#CurrentView").val() + ' col-xs-4 col-lg-4"><div class="thumbnail"><img class="group list-group-image" src="../img/product2.jpg" alt="" /><div class="caption"><h4 class="group inner list-group-item-heading">'; html += data[i].ProductName + '</h4><p class="group inner list-group-item-text"> Product description... </p><div class="row"><div class="col-xs-12 col-md-6"><p class="lead">'; html += data[i].UnitPrice + '</p></div><div class="col-xs-12 col-md-6"><a class="btn btn-success" href="http://www.jquery2dotnet.com">Add to cart</a></div></div></div></div></div>'; } html+= '</div>'; $(".clear").before(html); }); 键,它会向您的程序发送一个SIGINT(中断)。如果您没有特定的逻辑在程序关闭时运行它可能会完成这项工作。

如果您在程序关闭时运行某些逻辑,请检查this answer

答案 1 :(得分:1)

让我们清楚一点,你在客户端接受时阻止主线程。干净地关闭该计划将不是真正的方法。

我的解决方案是运行一个单独的线程,它将执行接受工作。

为了说明,这是我的代码:

这是接受线程:

private static Thread acception = new Thread("Acception Thread") {

    public void run() {

        try {
            while (true) {
                System.out.println("Waiting for Connection");
                new EchoServer2(serverSocket.accept());
            }
    ->  } catch (SocketException e) {
    ->      if(serverSocket.isClosed())
    ->          System.out.println("Connection Closed.");
    ->  }
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }

    }
};

这是修改后的main方法:

public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;


    try {
        serverSocket = new ServerSocket(2000);
        System.out.println("Connection Socket Created");
->      acception.start();
    } catch (IOException e) {
        System.err.println("Could not listen on port: 2000.");
        System.exit(1);
    }


    //support to close, using the command line.

    Scanner scn = new Scanner(System.in);
    String s = scn.next();

    while(true) {
        if("quit".equals.(s)) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                System.err.println("Could not close port: 2000.");
                System.exit(1);
            } finally {
                break;
            }
        }
        s = scn.next();
    }
}

答案 2 :(得分:0)

检查此链接http://www.oracle.com/technetwork/java/javase/signals-139944.html应该帮助您

编辑: 解决方案1:将其添加到主方法

Runtime.getRuntime().addShutdownHook(new Thread() {
   public void run() {
       System.out.println("Prepare to exit");
       //some cleaning up code...
   }
});

解决方案2:添加另一个等待“退出”命令的线程,类似于:

    new Thread() {
        @Override
        public void run() {
            System.out.println("Type exit to exit;-)");
            Console c = System.console();
            String msg = c.readLine();
            if (msg.equals("exit")) {
                //some cleaning up code...
                System.exit(0);                 
            }
        }
    }.start();