简体   繁体   English

如何关闭com.sun.net.httpserver.HttpServer?

[英]How to shutdown com.sun.net.httpserver.HttpServer?

The Http Server embedded in JDK 6 is a big help developing web services, but I've got situation where I published an Endpoint and then the code crashed and left the server running. 嵌入在JDK 6中的Http Server对于开发Web服务是一个很大的帮助,但我遇到的情况是我发布了一个Endpoint,然后代码崩溃并让服务器运行。

How do you shutdown the embedded server once you've lost the reference to it (or the published Endpoint)? 一旦丢失对它的引用(或已发布的端点),如何关闭嵌入式服务器?

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

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. 因此,有能力拦截此异常的人显然也需要引用HttpServer,您可能需要自己传递。

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, eg a command channel via RMI that can be invoked from a Java program (and hence Ant). 在这种情况下,如果您不想使用其中的HttpServer终止整个JVM,那么您将需要向环境提供某种形式的IPC,例如通过可以从Java程序调用的RMI的命令通道(和因此Ant)。

Another solution would be to have the server listen for some "secret" cookie query, where you eg 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. 另一个解决方案是让服务器监听一些“秘密”cookie查询,例如你在启动时打印/保存cookie,以便Ant脚本可以检索cookie,你可以启动查询到你的“秘密”URL服务器将优雅地退出自身。

I'd go with a quick RMI solution. 我会选择快速的RMI解决方案。

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. 看起来像com.sun.net.httpserver.HttpServer有一个名为HttpServerImpl的实现类。 It has a method called stop(). 它有一个名为stop()的方法。

Or perhaps you can find the Thread listening on the server socket and call interrupt(). 或者也许您可以在服务器套接字上找到线程侦听并调用interrupt()。

Sean 肖恩

netstat -a

to find the pid of the process that has the port open (assuming you know the port), and 找到打开端口的进程的pid(假设你知道端口),和

kill -9 $pid

to kill the process. 杀死这个过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM