Main.scala 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package example
  2. import java.util.Date
  3. import java.text.SimpleDateFormat
  4. import akka.actor.{Actor, ActorRef, Props}
  5. import akka.util.ByteString
  6. import scala.concurrent.duration._
  7. import colossus.IOSystem
  8. import colossus.core.{ServerRef, ServerSettings}
  9. import colossus.service._
  10. import colossus.protocols.http._
  11. import net.liftweb.json._
  12. import JsonDSL._
  13. object BenchmarkService {
  14. class Timestamp(server: ServerRef) extends Actor {
  15. val sdf = new SimpleDateFormat("EEE, MMM d yyyy HH:MM:ss z")
  16. case object Tick
  17. import context.dispatcher
  18. override def preStart() {
  19. self ! Tick
  20. }
  21. def receive = {
  22. case Tick => {
  23. server.delegatorBroadcast(sdf.format(new Date()))
  24. context.system.scheduler.scheduleOnce(1.second, self, Tick)
  25. }
  26. }
  27. }
  28. val response = ByteString("Hello, World!")
  29. val plaintextHeader = ("Content-Type", "text/plain")
  30. val jsonHeader = ("Content-Type", "application/json")
  31. val serverHeader = ("Server", "Colossus")
  32. def start(port: Int)(implicit io: IOSystem) {
  33. val serverConfig = ServerSettings(
  34. port = port,
  35. maxConnections = 16384,
  36. tcpBacklogSize = Some(1024)
  37. )
  38. val serviceConfig = ServiceConfig(
  39. name = "/sample",
  40. requestTimeout = Duration.Inf,
  41. requestMetrics = false
  42. )
  43. val server = Service.serve[Http](serverConfig, serviceConfig) { context =>
  44. ///the ??? is filled in almost immediately by the actor
  45. var dateHeader = ("Date", "???")
  46. context.receive {
  47. case ts: String => dateHeader = ("Date", ts)
  48. }
  49. context.handle { connection =>
  50. connection.become{ case request =>
  51. if (request.head.url == "/plaintext") {
  52. val res = HttpResponse(
  53. version = HttpVersion.`1.1`,
  54. code = HttpCodes.OK,
  55. data = response,
  56. headers = Vector(plaintextHeader, serverHeader, dateHeader)
  57. )
  58. Callback.successful(res)
  59. } else if (request.head.url == "/json") {
  60. val json = ("message" -> "Hello, World!")
  61. val res = HttpResponse(
  62. version = HttpVersion.`1.1`,
  63. code = HttpCodes.OK,
  64. data = compact(render(json)),
  65. headers = Vector(jsonHeader, serverHeader, dateHeader)
  66. )
  67. Callback.successful(res)
  68. } else {
  69. Callback.successful(request.notFound("invalid path"))
  70. }
  71. }
  72. }
  73. }
  74. val timestamp = io.actorSystem.actorOf(Props(classOf[Timestamp], server))
  75. }
  76. }
  77. object Main extends App {
  78. implicit val io_system = IOSystem()
  79. BenchmarkService.start(9007)
  80. }