Actually, I have the following problem in a WebSocket application, when I'm working with the dependency of JavaEE WebSocket API and I have the following component:
@ServerEndpoint("/echo")
public class Echo {
@OnMessage
public void onMessage(String message) {
LOG.info("Message received: " + msg);
String response = null;
try {
InputStream stream = getClass().getClassLoader().getResourceAsStream("image.jpg");
byte[] bytes = Base64.encodeBase64(IOUtils.toByteArray(stream));
response = String.format("data:image/jpg;base64,%s", new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
if (response != null) {
byte[] bytes = response.getBytes();
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, 0, bytes.length);
this.session.getAsyncRemote().sendBinary(byteBuffer);
} else {
LOG.info("Not sent message!");
}
}
}
This endpoint receives a text plane message, and after to load an image that I have in the Classpath
converting it into Base64
and to finally respond a BinaryFrame
with the image information.
I have a client code in HTML and Javascript, too.
var socket = new WebSocket('ws://localhost:8084/webdemo/echo');
socket.binaryType = "arrayBuffer";
socket.onopen = function (event) {
console.log('WebSocket connected!');
};
socket.onmessage = function (event) {
console.log('Message received', event.data);
};
function sendMessage() {
console.log('Send message.');
socket.send('This is a test message!');
}
sendMessage();
With this code I get the connection and send the following message "This is a test message!"
, this message is displayed on the server console. I show the BinaryFrame
's data type and in the web browser's console displayed Blob
.
Then, the question is:
How to send a BinaryFrame
response in the ArrayBuffer
format?
I don't want get Blob format.
I'm sorry if I have a bad english :S I'm studying it
UPDATE
The echo class:
@ServerEndpoint("/echo")
public class Echo {
@OnMessage
public void onMessage(String message) {
LOG.info("Message received: " + msg);
try {
InputStream stream = getClass().getClassLoader().getResourceAsStream("image.jpg");
byte[] bytes = IOUtils.toByteArray(stream);
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, 0, bytes.length);
this.session.getAsyncRemote().sendBinary(byteBuffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
After the update, encode the binary frame in base 64 and show image in <img>
tag.