Gradle HttpFileServer, keep running, but kill on ctrl+c

Viewed 546

During my Gradle build I need to run a simple web server to serve some static content. I’m using Gradle’s integrated classes for that.

Here's a very simple version of my build.gradle:

apply plugin: 'groovy'

task server() {
  doLast {
    def root = new File(project.buildDir, '/site')
    def port = 8765
    def factory = new SimpleHttpFileServerFactory();
    def server = factory.start(root, port)
    println "HTTP server started on $port"
  }
}

I'm facing the following two issues:

  • When running gradle server, gradle executes, starts the server, and then quits (with the daemon obviously staying in the background and the server running, which leads to the second problem)

  • I’ve no possibility to stop the server through gradle. When running gradle server again, I get an exception because the port is in use.

I’d fancy either of the following solutions:

  1. When running gradle server, gradle keeps running until I hit ctrl+c, then the server is killed as well

  2. There are two tasks, gradle startServer and gradle stopServer which are used to start and stop

How can I achieve this or is there a different, better solution?

1 Answers
Related