Created
December 19, 2015 14:34
-
-
Save dakatsuka/32c8809616d71e8d4ced to your computer and use it in GitHub Desktop.
akka-http + akka-atreamでWebSocketサーバを実装
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
name := "websocket-server" | |
version := "0.1.0" | |
scalaVersion := "2.11.7" | |
libraryDependencies ++= Seq( | |
"com.typesafe.akka" % "akka-stream-experimental_2.11" % "2.0-M2", | |
"com.typesafe.akka" % "akka-http-core-experimental_2.11" % "2.0-M2", | |
"com.typesafe.akka" % "akka-http-experimental_2.11" % "2.0-M2" | |
) |
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
import akka.actor.ActorSystem | |
import akka.stream.ActorMaterializer | |
import akka.stream.scaladsl._ | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.model._ | |
import akka.http.scaladsl.model.ws._ | |
import akka.http.scaladsl.model.HttpMethods._ | |
import scala.concurrent.Await | |
import scala.concurrent.duration.Duration | |
object Main extends App { | |
implicit val system = ActorSystem("websocket-server") | |
implicit val materializer = ActorMaterializer() | |
val echoFlow: Flow[Message, Message, Unit] = Flow[Message].mapConcat { | |
case tm: TextMessage => TextMessage(tm.textStream) :: Nil | |
case _ => Nil | |
} | |
val requestHandler: HttpRequest => HttpResponse = { | |
case req @ HttpRequest(GET, Uri.Path("/"), _, _, _) => | |
req.header[UpgradeToWebsocket] match { | |
case Some(upgrade) => upgrade.handleMessages(echoFlow) | |
case None => HttpResponse(400) | |
} | |
case _: HttpRequest => HttpResponse(400) | |
} | |
val binding = Http().bindAndHandleSync(requestHandler, interface = "localhost", port = 8080) | |
Await.ready(binding, Duration.Inf) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment