1
我試圖在Java EE 7中創建一個Websocket端點,該端點接收作爲輸入文件名並返回圖像的二進制數據。這裏的的WebSocket的Java方面:使用Websockets從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」並且屏幕上不顯示任何內容。 有人能找到罪魁禍首嗎? 謝謝!
好的!現在在Javascript端也接收到字節數。但屏幕上仍然沒有打印。所以在呈現Javascript中的字節時一定會有問題。 – user2824073