/src/main/scala/io/scalac/akka/http/websockets/Server.scala

https://github.com/ScalaConsultants/websocket-akka-http · Scala · 53 lines · 32 code · 18 blank · 3 comment · 2 complexity · e362e3ea9c891c7e831e790035acd001 MD5 · raw file

  1. package io.scalac.akka.http.websockets
  2. import akka.actor.ActorSystem
  3. import akka.http.scaladsl.Http
  4. import akka.http.scaladsl.server.Directives
  5. import akka.stream.ActorMaterializer
  6. import io.scalac.akka.http.websockets.services.{ChatService, EchoService, MainService}
  7. import scala.io.StdIn
  8. object Server extends App {
  9. import Directives._
  10. implicit val actorSystem = ActorSystem("akka-system")
  11. implicit val flowMaterializer = ActorMaterializer()
  12. val config = actorSystem.settings.config
  13. val interface = config.getString("app.interface")
  14. val port = config.getInt("app.port")
  15. val route = MainService.route ~
  16. EchoService.route ~
  17. ChatService.route
  18. val binding = Http().bindAndHandle(route, interface, port)
  19. println(s"Server is now online at http://$interface:$port\nPress RETURN to stop...")
  20. /**
  21. * Run WSClient when `with-client` argument is provided
  22. */
  23. alternativelyRunTheClient()
  24. StdIn.readLine()
  25. import actorSystem.dispatcher
  26. binding.flatMap(_.unbind()).onComplete(_ => actorSystem.shutdown())
  27. println("Server is down...")
  28. private def alternativelyRunTheClient(): Unit = {
  29. if (args.headOption.map(_.equalsIgnoreCase("with-client")).getOrElse(false)) {
  30. val c: WSClient = WSClient("http://localhost:8080/ws-chat/123?name=HAL1000", "HAL1000")
  31. if (c.connectBlocking())
  32. c.spam("hello message")
  33. }
  34. }
  35. }