handleWebSocketMessages
Description
The directive first checks if the request was a valid WebSocket handshake request and if yes, it completes the request with the passed handler. Otherwise, the request is rejected with an ExpectedWebSocketRequestRejection.
WebSocket subprotocols offered in the Sec-WebSocket-Protocol
header of the request are ignored. If you want to support several protocols use the handleWebSocketMessagesForProtocol directive, instead.
For more information about the WebSocket support, see Server-Side WebSocket Support.
Example
- Scala
-
def greeter: Flow[Message, Message, Any] = Flow[Message].mapConcat { case tm: TextMessage => TextMessage(Source.single("Hello ") ++ tm.textStream ++ Source.single("!")) :: Nil case bm: BinaryMessage => // ignore binary messages but drain content to avoid the stream being clogged bm.dataStream.runWith(Sink.ignore) Nil } val websocketRoute = path("greeter") { handleWebSocketMessages(greeter) } // tests: // create a testing probe representing the client-side val wsClient = WSProbe() // WS creates a WebSocket request for testing WS("/greeter", wsClient.flow) ~> websocketRoute ~> check { // check response for WS Upgrade headers isWebSocketUpgrade shouldEqual true // manually run a WS conversation wsClient.sendMessage("Peter") wsClient.expectMessage("Hello Peter!") wsClient.sendMessage(BinaryMessage(ByteString("abcdef"))) wsClient.expectNoMessage(100.millis) wsClient.sendMessage("John") wsClient.expectMessage("Hello John!") wsClient.sendCompletion() wsClient.expectCompletion() }
- Java