extractUpgradeToWebSocket

Description

Extracts the UpgradeToWebSocket header if existent. Rejects with an ExpectedWebSocketRequestRejection, otherwise.

The extractUpgradeToWebSocket directive is used as a building block for Custom Directives to provide the extracted header to the inner route.

Example

final Flow<Message, Message, NotUsed> echoService = Flow.of(Message.class).buffer(1, OverflowStrategy.backpressure());

final Route websocketRoute = path("services", () ->
  route(
    extractUpgradeToWebSocket(upgrade ->
      complete(upgrade.handleMessagesWith(echoService, "echo"))
    )
  )
);

// tests:
// create a testing probe representing the client-side
final WSProbe wsClient = WSProbe.create(system(), materializer());

// WS creates a WebSocket request for testing
testRoute(websocketRoute)
  .run(WS(Uri.create("/services"), wsClient.flow(), materializer(), Collections.emptyList()))
  .assertHeaderExists(SecWebSocketProtocol.create("echo"));

wsClient.sendMessage("ping");
wsClient.expectMessage("ping");

wsClient.sendCompletion();
wsClient.expectCompletion();
The source code for this page can be found here.