dimanche 3 janvier 2016

Not getting proper Image display using Web socket Api in chat application

I am building a chat application using web socket api introduced in javaEE 7. I have been able to send text messages in chat successfully but when I'm sending images over chat, image is not displayed properly. Instead of image some random dots are showing on screen. I'm sending inputstream to server and then broadcasting the message to all the active sessions. In the javascript api, i'm creating a canvas and attaching image to it. But image is not showing properly. Please refer my code below:

    **my base.js class:**

    $(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();
        });
    });

    **My xhtml class:**

    <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">
    <ui:composition xmlns="http://ift.tt/lH0Osb"
                    xmlns:h="http://ift.tt/J1LPWj"
                    xmlns:jsf="http://ift.tt/1mQKsXW"
                    xmlns:ui="http://ift.tt/1g9HgFb"
                    xmlns:f="http://ift.tt/19DXC4H"
                    template="/template/default.xhtml"
                    xmlns:c="http://ift.tt/1kyxZva">

        <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>

    **My server end point class:**

    @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);
            }
        }

Can anybody help me find out what's the issue...
I have tries almost everything but could not make it work.
Thanks in advance!!!




Aucun commentaire:

Enregistrer un commentaire