How to shutdown com.sun.net.httpserver.HttpServer?

瘦欲@ 提交于 2019-12-03 03:47:55

I use the below code to start it

    this.httpServer = HttpServer.create(addr, 0);
    HttpContext context = this.httpServer.createContext("/", new DocumentProcessHandler());
    this.httpThreadPool = Executors.newFixedThreadPool(this.noOfThreads);
    this.httpServer.setExecutor(this.httpThreadPool);
    this.httpServer.start();

and below code to stop it

        this.httpServer.stop(1);
        this.httpThreadPool.shutdownNow();

I've never used this server before and I can't find any good documentation. Perhaps these less elegant solutions have occurred to you already, but I just thought I would mention them.

Seems like com.sun.net.httpserver.HttpServer has an implementation class called HttpServerImpl. It has a method called stop().

Or perhaps you can find the Thread listening on the server socket and call interrupt().

Sean

How about not loosing the reference, then? When you say your code crashes, I assume you get an exception somewhere. Where exactly? So someone capable of intercepting this exception obviously needs to also have a reference to the HttpServer, which you might have to pass around yourself.

Edit: Oh. In that case if you don't want to kill the entire JVM with the HttpServer in it, then you will need to offer some form of IPC to the environment, e.g. a command channel via RMI that can be invoked from a Java program (and hence Ant).

Another solution would be to have the server listen for some "secret" cookie query, where you e.g. print/save the cookie on startup so that the Ant script can retrieve the cookie, and you can fire off a query to your "secret" URL upon which the server will exit itself gracefully.

I'd go with a quick RMI solution.

netstat -a

to find the pid of the process that has the port open (assuming you know the port), and

kill -9 $pid

to kill the process.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!