TakahikoKawasaki / nv-websocket-client

High-quality WebSocket client implementation in Java.
Apache License 2.0
2.03k stars 292 forks source link

Avoid string allocation by providing a mechanism for listeners to receive binary text data #171

Closed willtemperley closed 5 years ago

willtemperley commented 5 years ago

Currently, when a text frame is received, ReadingThread automatically converts this to a UTF8 String. This is obviously expected behaviour for most use cases, but in my use case I'll immediately parse this information using a library which will call String.getBytes().

That's a lot of un-necessary work, which can be entirely avoided by receiving the byte[] directly.

I have hacked ReadingThread.callOnTextMessage(byte[] data) myself to call ReadingThread.onBinaryMessage(byte[]) to bypass the string allocation, however it would be great if there was a standard mechanism to directly obtain the byte[] when it's a text message.

(Thanks for a great library by the way!)

TakahikoKawasaki commented 5 years ago

Released nv-websocket-client 2.6 including the feature described below.


Direct Text Message

When a text message was received, onTextMessage(WebSocket, String) is called. The implementation internally converts the byte array of the text message into a String object before calling the listener method. If you want to receive the byte array directly without the string conversion, call setDirectTextMessage(boolean) with true, and onTextMessage(WebSocket, byte[]) will be called instead.

// Receive text messages without string conversion.
ws.setDirectTextMessage(true);
willtemperley commented 5 years ago

That's excellent, thanks, exactly what I was hoping for. This should provide a significant performance boost.