Skip to content

Instantly share code, notes, and snippets.

@jrudolph
Forked from minchenkov/spray-chunked-test.scala
Created October 3, 2013 08:14
Show Gist options
  • Save jrudolph/6806801 to your computer and use it in GitHub Desktop.
Save jrudolph/6806801 to your computer and use it in GitHub Desktop.
package ru.metahouse.metabus
import akka.actor._
import akka.io.IO
import spray.can.Http
import spray.routing.HttpServiceActor
import spray.http._
import spray.http.MediaTypes._
import scala.concurrent.ExecutionContext.Implicits.global
import spray.http.ChunkedResponseStart
import spray.http.HttpResponse
import scala.concurrent.duration._
object Program {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem("test")
val frontend = system.actorOf(Props[HttpService], name = "frontend")
IO(Http) ! Http.Bind(frontend, interface = "127.0.0.1", port = 8282)
}
}
class HttpService extends HttpServiceActor with ActorLogging {
def receive = runRoute(
path("test") {
get {
complete {
<html>
<body>
<form method="post"><input type="submit"></input></form>
</body>
</html>
}
} ~
post {
request =>
context.actorOf(Props(new TestStream(request.responder)))
}
}
)
}
class TestStream(responder: ActorRef) extends Actor with ActorLogging{
private case class Timer(n: Int)
private val header = (1 to 1024).map(_ => "\uFEFF").mkString("")
self ! Timer(200)
responder ! ChunkedResponseStart(
HttpResponse(entity = HttpEntity(ContentType(`text/plain`, HttpCharsets.`UTF-8`), header)))
def receive = {
case Timer(0) =>
responder ! ChunkedMessageEnd()
context.stop(self)
case Timer(n) =>
responder ! MessageChunk(n.toString + "\n")
context.system.scheduler.scheduleOnce(1 second, self, Timer(n - 1))
case ev: Http.ConnectionClosed =>
log.debug("connection closed")
context.stop(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment