簡體   English   中英

使用Websocket從Java端點發送圖像

[英]Sending an Image from Java endpoint using Websockets


我正在嘗試在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”,並且屏幕上沒有呈現任何內容。 有人能找到罪魁禍首嗎? 謝謝!

您在客戶端上不見了:

websocket.binaryType =“ arraybuffer”;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM