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.
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();
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.
来源:https://stackoverflow.com/questions/928211/how-to-shutdown-com-sun-net-httpserver-httpserver