Last active
February 17, 2017 12:00
-
-
Save note/b7869c1a72baa0a4c583c400f7bda919 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import akka.actor.ActorSystem | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.model._ | |
import akka.http.scaladsl.server.Directives._ | |
import akka.stream.{ActorMaterializer, Materializer} | |
import akka.stream.scaladsl.{Sink, Source, StreamConverters} | |
import akka.util.ByteString | |
import scala.io.StdIn | |
object WebServer { | |
def main(args: Array[String]) { | |
implicit val system = ActorSystem("my-system") | |
implicit val materializer = ActorMaterializer() | |
implicit val executionContext = system.dispatcher | |
val route = | |
path("stream") { | |
get { | |
source.runWith(Sink.foreach(str => println(s"Some string: ${str.utf8String}"))) | |
val httpEntity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, source) | |
complete(httpEntity) | |
} | |
} | |
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) | |
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...") | |
StdIn.readLine() // let it run until user presses return | |
bindingFuture | |
.flatMap(_.unbind()) // trigger unbinding from the port | |
.onComplete(_ => system.terminate()) // and shutdown when done | |
} | |
private def source: Source[ByteString, Unit] = { | |
StreamConverters.asOutputStream().mapMaterializedValue { os => | |
os.write("test hello 33".getBytes) | |
os.close() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment