Problem Using getStrictText in handleWebSocketMessages for not stricted message

Hello, I try to use Akka Http server with websocket handling in Java code.
I’v used a handleWebSocketMessages directive as is in the akka doc. site:
https://doc.akka.io/docs/akka-http/current/server-side/websocket-support.html

The problem is when I get the message and it is not stricted (long text - 5k) I cannot get a text message of it (I tried to call TextMessage.create(source).getStrictText())

The code of handleTextMessage fuctions is:

public static TextMessage handleTextMessage(TextMessage msg) {
String msgText = “”;
if (msg.asTextMessage().isStrict())
{
msgText = msg.asTextMessage().getStrictText();
} else {
Source<String,NotUsed> source = Source.single("").concat(msg.asTextMessage().getStreamedText());
msgText = TextMessage.create(source).getStrictText();
//handling of msgText …
}
}

I tried also to use toStrict and fold methods, but it always failed with timeout exception:
String str = TextMessage.create(source).toStrict(10000,materializer).toCompletableFuture().get().getStrictText();
or
String str =TextMessage.create(source).getStreamedText().fold("", (s1,s2)->(s1+s2)).toString();

How can I extract the text message?
Thanks.

You will have to fold the tet however, note that it will be a stream of chunks, not a list of text. You will have to run that stream. You can see a sample in the docs here: https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/websocket-directives/handleWebSocketMessages.html

Thank you for the answer.
Eventually I’ve used the next code since runFold method had blocked the the “Flow” thread in the case of “unstricted” message

StringBuilder _sb = new StringBuilder();
public static TextMessage handleTextMessage(TextMessage msg) {

msg.asTextMessage().getStreamedText()
.runForeach((msgPart)->_sb.append(msgPart), materializer)
.thenAccept((don1)->{
String clientMsgText = _sb.toString();
//user of clientMsgText;
});

I forgot that we actually have toStrict on those Message APIs since Akka HTTP 10.1.2 which does the folding for you.

toStrict does use a timeout which is at least some level of protection against a client filling your memory by just streaming a very large amount of text in one message. If using your own folding, make sure you put a limit in there.

Often (but not always) you’ll want to deal with the folded complete message CompletionStage in stream so that you can reply to the sending side, you can achieve this by doing the transformation in a .mapAsync in the WS-handling flow instead of side-effecting from thenAccept.

1 Like