[java] respect the last flag for binary data
respect the last flag for binary data
Respect the last flag for binary data to ensure the listener will get a
complete message and not only a partial message.
[skip ci]
import org.openqa.selenium.remote.http.TextMessage;
import org.openqa.selenium.remote.http.WebSocket;
-import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
@@ -127,6 +126,7 @@ public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) {
uri,
new java.net.http.WebSocket.Listener() {
final StringBuilder builder = new StringBuilder();
+ final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
@Override
public CompletionStage<?> onText(java.net.http.WebSocket webSocket, CharSequence data, boolean last) {
@@ -145,11 +145,21 @@ public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) {
@Override
public CompletionStage<?> onBinary(java.net.http.WebSocket webSocket, ByteBuffer data, boolean last) {
- LOG.fine("Binary data received.");
- byte[] ary = new byte[data.remaining()];
- data.get(ary, 0, ary.length);
+ LOG.fine("Binary data received. Appending data");
+ byte[] ary = new byte[8192];
- listener.onBinary(ary);
+ while (data.hasRemaining()) {
+ int n = Math.min(ary.length, data.remaining());
+ data.get(ary, 0, n);
+ buffer.write(ary, 0, n);
+ }
+
+ if (last) {
+ LOG.fine("Final part of binary data received. Calling listener with "
+ + buffer.size() + " bytes of data");
+ listener.onBinary(buffer.toByteArray());
+ buffer.reset();
+ }
webSocket.request(1);
return null;
}
