/scala/akka-http/sample_websocket/src/main/scala/SampleApp.scala

https://github.com/fits/try_samples · Scala · 43 lines · 34 code · 9 blank · 0 comment · 0 complexity · b614b75ddaaecadd35997941a67a4800 MD5 · raw file

  1. import akka.actor.ActorSystem
  2. import akka.http.scaladsl.Http
  3. import akka.http.scaladsl.model.ws.{Message, TextMessage}
  4. import akka.http.scaladsl.server.Directives._
  5. import akka.stream.ActorMaterializer
  6. import akka.stream.scaladsl.Flow
  7. import scala.concurrent.ExecutionContext
  8. import scala.io.StdIn
  9. object SampleApp extends App {
  10. implicit val system: ActorSystem = ActorSystem("sample")
  11. implicit val executionContext: ExecutionContext = system.dispatcher
  12. implicit val materializer: ActorMaterializer = ActorMaterializer()
  13. val websocketFlow = { name: String =>
  14. Flow[Message].collect {
  15. case TextMessage.Strict(msg) =>
  16. println(s"*** receive $name: $msg")
  17. TextMessage.Strict(s"$name: $msg")
  18. }
  19. }
  20. val route = get {
  21. pathSingleSlash {
  22. getFromResource("web/index.html")
  23. } ~
  24. path("sample") {
  25. parameter("name") { name =>
  26. handleWebSocketMessages(websocketFlow(name))
  27. }
  28. }
  29. }
  30. val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
  31. println("started server ...")
  32. StdIn.readLine()
  33. bindingFuture.flatMap(_.unbind).onComplete(_ => system.terminate())
  34. }