-1

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:

Javascript code:

    $(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 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!!!

Alexander Rühl
  • 6,769
  • 9
  • 53
  • 96
Prateek Sharma
  • 109
  • 2
  • 9

1 Answers1

0

Try using Base64 encoding when sending.

Check out the answer to this question.

Community
  • 1
  • 1
Alexander Rühl
  • 6,769
  • 9
  • 53
  • 96