We have a simple use case of sending an infinite stream in response whenever the websocket route receives any message. For the same, I wrote the below server code and simple client (executed in Chrome browser console). It works, but when I call ws.close()
from browser, the websocket stream does not terminate and the browser keeps receiving messages till the idle-timeout
is triggered.
Am I missing something here or is this not the right way to do it?
Code snippets:
- Server code
object HttpApp extends App {
implicit val system: ActorSystem[SpawnProtocol.Command] = ActorSystem(SpawnProtocol(), "test")
import system.executionContext
private val handler: Flow[Message, TextMessage.Strict, Unit] = Flow[Message]
.flatMapConcat({ msg =>
println(msg)
Source.tick(0.seconds, 1.seconds, msg).map(TextMessage(_).tap(println))
})
.watchTermination() { (_, doneF) => doneF.onComplete(_ => println("concatenated stream closed")) }
val route = Directives.path("hello")(Directives.handleWebSocketMessages(handler))
Http().newServerAt("0.0.0.0", 8998).bind(route)
}
- Client code: Execute below code on browser console
ws = new WebSocket("ws://localhost:8998/hello")
ws.onclose = (a) => console.log("closed" + a)
ws.onmessage= (m)=> console.log(m)
and then execute
ws.close()