extractUpgradeToWebSocket

Signature

def extractUpgradeToWebSocket: Directive1[UpgradeToWebSocket]

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

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") {
    extractUpgradeToWebSocket { 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()
  }
}
The source code for this page can be found here.