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

前端 未结 4 1787
暗喜
暗喜 2021-02-10 12:34

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 runn

相关标签:
4条回答
  • 2021-02-10 13:15

    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

    0 讨论(0)
  • 2021-02-10 13:19

    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();
    
    0 讨论(0)
  • 2021-02-10 13:19

    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.

    0 讨论(0)
  • 2021-02-10 13:21
    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.

    0 讨论(0)
提交回复
热议问题