Created
December 17, 2017 22:18
-
-
Save ayushmishra2005/1bbace9de593811849a810752e601505 to your computer and use it in GitHub Desktop.
Akka HTTP WebSocket example using high-level routing DSL
This file contains 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.tutorial.sample | |
import akka.http.scaladsl.model.ws.{Message, TextMessage} | |
import akka.http.scaladsl.server.Directives | |
import akka.stream.scaladsl.{Flow, Source} | |
trait HighLevelWebSocketSample extends Directives { | |
def route = | |
path("chat") { | |
parameter('name) { name ⇒ | |
handleWebSocketMessages(broadcast(name)) | |
} | |
} | |
def broadcast(name: String): Flow[Message, Message, Any] = { | |
Flow[Message].mapConcat { | |
case tm: TextMessage => | |
TextMessage(Source.single(name + "::") ++ tm.textStream) :: Nil | |
} | |
} | |
} | |
import akka.http.scaladsl.testkit.{ScalatestRouteTest, WSProbe} | |
import org.scalatest.{Matchers, WordSpec} | |
class HighLevelWebSocketSampleTest extends WordSpec with Matchers with ScalatestRouteTest with HighLevelWebSocketSample{ | |
"Websocket" should { | |
"be able to pull and push message" in { | |
val wsClient = WSProbe() | |
WS("/chat?name=Chris", wsClient.flow) ~> route ~> | |
check { | |
isWebSocketUpgrade shouldEqual true | |
wsClient.sendMessage("How are you?") | |
wsClient.expectMessage("Chris::How are you?") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment