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

final Flow<Message, Message, NotUsed> greeter = Flow.of(Message.class).mapConcat(msg -> {
  if (msg instanceof TextMessage) {
    final TextMessage tm = (TextMessage) msg;
    final TextMessage ret = TextMessage.create(Source.single("Hello ").concat(tm.getStreamedText()).concat(Source.single("!")));
    return Collections.singletonList(ret);
  } else if (msg instanceof BinaryMessage) {
    final BinaryMessage bm = (BinaryMessage) msg;
    bm.getStreamedData().runWith(Sink.ignore(), materializer());
    return Collections.emptyList();
  } else {
    throw new IllegalArgumentException("Unsupported message type!");
  }
});

final Route websocketRoute = path("greeter", () ->
  handleWebSocketMessages(greeter)
);

// 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("/greeter"), wsClient.flow(), materializer()))
  .assertStatusCode(StatusCodes.SWITCHING_PROTOCOLS);

// manually run a WS conversation
wsClient.sendMessage("Peter");
wsClient.expectMessage("Hello Peter!");

wsClient.sendMessage(BinaryMessage.create(ByteString.fromString("abcdef")));
wsClient.expectNoMessage(FiniteDuration.create(100, TimeUnit.MILLISECONDS));

wsClient.sendMessage("John");
wsClient.expectMessage("Hello John!");

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