extractUpgradeToWebSocket

Signature

def extractUpgradeToWebSocket: Directive1[UpgradeToWebSocket] 

Description

This directive is deprecated, see extractWebSocketUpgrade instead.

If you are looking for a building block for Custom Directives to provide the websocket upgrade information to the inner route, we recommend using the WebSocketUpgradeWebSocketUpgrade attribute instead:

Scala
sourceimport org.apache.pekko.http.scaladsl.model.AttributeKeys.webSocketUpgrade

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") {
    extractWebSocketUpgrade { upgrade =>
      complete(upgrade.handleMessages(echoService, Some("echo")))
    }
  }

// tests:
val wsClient = WSProbe()

// WS creates a WebSocket request for testing
WS("/services", wsClient.flow, Nil) ~> route ~> check {
  expectWebSocketUpgradeWithProtocol { protocol =>
    protocol shouldEqual "echo"
    wsClient.sendMessage("ping")
    wsClient.expectMessage("ping")
    wsClient.sendCompletion()
    wsClient.expectCompletion()
  }
}
Java
sourcefinal Flow<Message, Message, NotUsed> echoService =
    Flow.of(Message.class).buffer(1, OverflowStrategy.backpressure());

final Route websocketRoute =
    path(
        "services",
        () ->
            concat(
                extractWebSocketUpgrade(
                    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();