extractOfferedWsProtocols
Description
Extracts the list of WebSocket subprotocols as offered by the client in the Sec-WebSocket-Protocol
header if this is a WebSocket request. Rejects with an ExpectedWebSocketRequestRejection
ExpectedWebSocketRequestRejection
, otherwise.
The extractOfferedWsProtocols
directive is used as a building block for Custom Directives to provide the extracted protocols to the inner route.
Example
- Scala
-
source
def echoService: Flow[Message, Message, Any] = Flow[Message] // needed because a noop flow hasn't any buffer that would start processing in tests .buffer(1, OverflowStrategy.backpressure) def route = path("services") { extractOfferedWsProtocols { protocols => handleWebSocketMessagesForOptionalProtocol(echoService, protocols.headOption) } } // tests: val wsClient = WSProbe() // WS creates a WebSocket request for testing WS("/services", wsClient.flow, List("echo", "alfa", "kilo")) ~> route ~> check { expectWebSocketUpgradeWithProtocol { protocol => protocol shouldEqual "echo" wsClient.sendMessage("ping") wsClient.expectMessage("ping") wsClient.sendCompletion() wsClient.expectCompletion() } }
- Java
-
source
import static org.apache.pekko.http.javadsl.server.Directives.extractOfferedWsProtocols; import static org.apache.pekko.http.javadsl.server.Directives.handleWebSocketMessagesForOptionalProtocol; final Flow<Message, Message, NotUsed> echoService = Flow.of(Message.class).buffer(1, OverflowStrategy.backpressure()); final Route websocketRoute = path( "services", () -> concat( extractOfferedWsProtocols( protocols -> handleWebSocketMessagesForOptionalProtocol( echoService, protocols.stream().findFirst())))); // tests: // create a testing probe representing the client-side final WSProbe wsClient = WSProbe.create(system(), materializer()); testRoute(websocketRoute) .run( WS( Uri.create("/services"), wsClient.flow(), materializer(), Arrays.asList("echo", "alfa", "kilo"))) .assertHeaderExists(SecWebSocketProtocol.create("echo")); wsClient.sendMessage("ping"); wsClient.expectMessage("ping"); wsClient.sendCompletion(); wsClient.expectCompletion();
1.1.0+17-3b5f9b27*