Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scalatra: chunked transfer Encoding HTTP endpoint example
#
# a simple client for the endpoint.
#
import requests
import time
r = requests.get("http://localhost:8080/chunks", stream=True)
t0 = time.time()
for message in r.iter_lines(chunk_size=1):
print("At %d s, recieved: %s" % (time.time()-t0, message.decode("utf-8")))
import org.json4s.{DefaultFormats, Formats}
import scala.language.postfixOps
import scalate.ScalateSupport
import org.scalatra._
import java.io.PrintWriter
class Chunks extends ScalatraServlet with ScalateSupport {
/*
Simple example of chunked transfer encoding in Scalatra (scala web framework)
*/
get("/") {
response.setHeader("Content-Type", "text/html")
response.setHeader("Transfer-Encoding", "chunked")
response.setStatus(200)
val out = response.getWriter
0 to 100 foreach { i=>
sendMessage(s"Hello! This is message $i.", out)
Thread.sleep(1000)
}
}
def sendMessage(message:String, output:PrintWriter): Unit = {
output.println(message)
output.flush()
println("SENT: " + message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment