1
votes

I have following code:

val serverSource = Http().bind("localhost", 8080)
val connectionSink = Sink.foreach[IncomingConnection] {
    connection => println(s"Accepted incoming connection from ${connection.remoteAddress}")
  }
val serverBindingFuture = serverSource.to(connectionSink).run()
serverBindingFuture.onComplete {
    case Success(binding) => {
      println("Server binding successful")
      binding.terminate(10 seconds)
    }
    case Failure(ex) => println(s"Server binding failed $ex")
}

As the snippet tells, I am terminating the server binding after 10 seconds. So I expect that if I send the request before this period expires, I should get message 'Accepted incoming connection from...' printed.

But I observe that I always get 'This site can’t be reached', and message is never printed.

1

1 Answers

1
votes

As the snippet tells, I am terminating the server binding after 10 seconds. So I expect that if I send the request before this period expires, I should get message 'Accepted incoming connection from...' printed.

You've misunderstood the semantics of terminate. The duration argument is a hard deadline for shutdown, not an indication that the server will continue accepting requests until then.

Here's a tweak to your code to demonstrate this.

  • print Server binding successful as soon as the server is up and wait 10 seconds before calling terminate
  • print Starting shutdown right before calling terminate and print Finished shutdown as soon as the terminate completes

You should see:

  • curl 'http://localhost:8080/api triggers the println until Starting shutdown appears
  • the delay between Starting shutdown and Finished shutdown is likely to be quite short (much shorter that 10 seconds)
val serverSource = Http().bind("localhost", 8080)
val connectionSink = Sink.foreach[IncomingConnection] {
  connection => println(s"Accepted incoming connection from ${connection.remoteAddress}")
}
val serverBindingFuture = serverSource.to(connectionSink).run()
serverBindingFuture.onComplete {
  case Success(binding) => {
    println("Server binding successful")
    system.scheduler.scheduleOnce(10 seconds) {
      println("Starting shutdown")
      binding.terminate(10 seconds).onComplete { termOutcome =>
        println(s"Finished shutdown $termOutcome")
      }
    }
  }
  case Failure(ex) => println(s"Server binding failed $ex")
}