在聊天应用程序中使用Web套接字Api无法正确显示图像

时间:2016-01-04 07:24:42

标签: web websocket java-ee-7

我正在使用javaEE 7中引入的web socket api构建聊天应用程序。我已经能够成功地在聊天中发送短信但是当我通过聊天发送图像时,图像显示不正确。而不是图像在屏幕上显示一些随机点。我将输入流发送到服务器,然后将消息广播到所有活动会话。在javascript api中,我创建了一个画布并将图像附加到它上面。但图像显示不正确。 请参考下面的代码:

Javascript代码:

    $(document).ready(function () {
        var name = document.getElementById('inputForm:senderName').value;
        var pathName = window.location.pathname.split('/');
        var ws = new WebSocket("ws://localhost:8080/"+pathName[1]+ "/serverEndPoint/"+name);
        ws.binaryType = "arraybuffer";
        // Listen for the connection open e then call the sendMessage function
        ws.onopen = function (e) {
            $("#infoArea").append("<p>Connected</p>");
        };

        // Listen for the close connection e
        ws.onclose = function (e) {
            $("#infoArea").append("<p>Disconnected: " + e.reason + "</p>");

        };

        // Listen for connection errors
        ws.onerror = function (e) {
            $("#infoArea").append("<p>Error</p>");
        };

        // Listen for new messages arriving at the client
        ws.onmessage = function (e) {
                var bytes = new Uint8Array(event.data);
                var canvas = document.createElement('canvas');
                var context = canvas.getContext("2d");
                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();
                img.style.border = 'red';
                canvas.appendChild(img);
                document.getElementById('infoArea').appendChild(canvas);

        };

        $("#inputForm\\:enterButton").click(function () {
            var subject = document.getElementById('inputForm:chatMessage').value;
            document.getElementById('inputForm:chatMessage').value = null;
            var json = {
                'messageContent': subject
            };
            ws.send(JSON.stringify(json));
            return false;
        });

        var textArea = $("#inputForm\\:chatMessage")[0];
        textArea.addEventListener("dragover", function(e){
            e.preventDefault();
        });
        textArea.addEventListener("drop", function(e){
            e.preventDefault();
            var file= e.dataTransfer.files[0];

            var reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onload = function(){
                ws.send(reader.result);
            };
        });

        $("#close").click(function () {
            ws.close();
        });
    });

XHTML:

    <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <ui:composition xmlns="http://www.w3.org/1999/xhtml"
                    xmlns:h="http://xmlns.jcp.org/jsf/html"
                    xmlns:jsf="http://xmlns.jcp.org/jsf"
                    xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
                    xmlns:f="http://xmlns.jcp.org/jsf/core"
                    template="/template/default.xhtml"
                    xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">

        <ui:define name="content">
            <form jsf:id="inputForm" >
                <input type="text" jsf:id="userName"  value="#{inputBean.name}"/>
                <input type="submit" jsf:id="press" value="enter chat" action="#{inputBean.next()}"/>
            </form>
        </ui:define>
    </ui:composition>

Java服务器端点类:

    @OnMessage
        public void onBinaryMessage(Session session, InputStream inputStream) {
            try {
                byte[] bytes = IOUtils.toByteArray(inputStream);
                for (Session s : session.getOpenSessions()) {
                    if (s.isOpen()) {
                        s.getBasicRemote().sendBinary(ByteBuffer.wrap(bytes));
                    }
                }
            } catch (IOException ex) {
                SystemLogger.getInstance().error("Exception occur in onMessage Method at Server Side due to: " + ex.getMessage());
                throw new RuntimeException(ex.getMessage(), ex);
            }
        }

任何人都可以帮我找出问题所在...... 我几乎尝试了所有东西,但无法使其发挥作用。 在此先感谢!!!

1 个答案:

答案 0 :(得分:0)

发送时尝试使用Base64编码。

查看this question的答案。