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



我正在使用javaEE7中引入的web套接字api构建一个聊天应用程序。我可以在聊天中成功发送短信,但当我在聊天中发送图像时,图像无法正确显示。屏幕上显示的不是图像,而是一些随机的点。我将inputstream发送到服务器,然后将消息广播到所有活动会话。在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);
            }
        }

有人能帮我找出问题出在哪里吗。。。我几乎什么都试过了,但没能成功。提前感谢!!!

发送时请尝试使用Base64编码。

看看这个问题的答案。

相关内容

  • 没有找到相关文章

最新更新