我正在尝试在Java EE 7中创建一个Websocket端点,它接收文件名作为输入并返回图像的二进制数据。这是Websocket的Java端:
@ServerEndpoint(value = "/hellobinary")
public class HelloWorldBinaryEndpoint {
@OnMessage
public void hello(String img, Session session) {
File fi = new File("C:\\Users\\\images\\"+img);
byte[] fileContent=null;
try {
fileContent = Files.readAllBytes(fi.toPath());
ByteBuffer buf = ByteBuffer.wrap(fileContent);
session.getBasicRemote().sendBinary(buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这是它的Javascript方面:
var wsUri = "ws://localhost:8080/websocket/hellobinary";
function init() {
output = document.getElementById("output");
}
function send_message() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
onOpen(evt)
};
websocket.onmessage = function(evt) {
onMessage(evt)
};
websocket.onerror = function(evt) {
onError(evt)
};
}
function onOpen(evt) {
writeToScreen("Connected to Endpoint!");
doSend(textID.value);
}
function onMessage(evt) {
drawImageBinary(evt.data);
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("Message Sent: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
function drawImageBinary(blob) {
var bytes = new Uint8Array(blob);
alert('received '+ bytes.length);
var imageData = context.createImageData(canvas.width, canvas.height);
for (var i=8; i<imageData.data.length; i++) {
imageData.data[i] = bytes[i];
}
context.putImageData(imageData, 0, 0);
var img = document.createElement('img');
img.height = canvas.height;
img.width = canvas.width;
img.src = canvas.toDataURL();
}
window.addEventListener("load", init, false);
由于从Java端正确读取了图像(至少读取的字节数是正确的),我认为问题出在JavaScript端。
我添加了一个警报来记录drawImageBinary中读取的字节数,但是打印“0”并且屏幕上没有任何内容呈现。
有人能找到罪魁祸首吗?
谢谢!
答案 0 :(得分:2)
客户端缺少:
websocket.binaryType =“arraybuffer”;