Websocket通过Javascript客户端发送图像文件

时间:2019-05-29 14:48:04

标签: javascript java tomcat websocket

我正在编写一个简单的应用程序,其中javascript web套接字客户端必须将图像发送到由tomcat和Java语言实现的webscoket。 当我发送字符串消息时,一切正常,但是如果我发送图像数据,则不会触发@Onmessage事件。我已经花了2天了,但是还没有解决方案。

Java WebSocket代码:

@ServerEndpoint("/sendfile")
public class BinaryWebSocketServer {
    private
    static final Set<Session> sessions =
    Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("onOpen_File::" + session.getId());        
    }
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("onClose_File::" +  session.getId());
    }

    @OnMessage
    public void onMessage(byte[] data, Session session) {
        System.out.println("onByteArrayMessage::From=" + session.getId() + " with len:" + data.length );
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        BufferedImage bImage2;
        try {
            bImage2 = ImageIO.read(bis);
             ImageIO.write(bImage2, "jpg", new File("output.jpg") );
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        System.out.println("image created");

    }


    @OnError
    public void onError(Throwable t) {
        System.out.println("onError::" + t.getMessage());
    }

}

JavaScript客户端:

<body>
    <h2>File Upload</h2>   Select file

    <input type="file" id="filename" />

    <br>

    <input type="button" value="Connect" onclick="connectChatServer()" />

    <br>

    <input type="button" value="Upload" onclick="sendFile()" />
     <input onclick="wsCloseConnection();" value="Disconnect" type="button">
    <br />
    <textarea id="echoText" rows="5" cols="30"></textarea>
    <script>

    var webSocket = new WebSocket("ws://192.168.1.55:8081/Hello-Capture/sendfile");
    webSocket.binaryType = 'arraybuffer';
    webSocket.onopen = function(message){ wsOpen(message);};
    //webSocket.onmessage = function(message){ wsGetMessage(message);};
    webSocket.onclose = function(message){ wsClose(message);};
    webSocket.onerror = function(message){ wsError(message);};
    function wsOpen(message){
        echoText.value += "Connected ... \n";
    }
    function wsSendMessage(){
        webSocket.send(message.value);
        echoText.value += "Message sended to the server : " + message.value + "\n";
        message.value = "";
    }
    function wsCloseConnection(){
        webSocket.close();
    }
    function wsGetMessage(message){
        echoText.value += "Message received from to the server : " + message.data + "\n";
    }
    function wsClose(message){
        echoText.value += "Disconnect ... \n";
    }

    function wsError(message){
        echoText.value += "Error ..." + message.code +" \n";
    }


        function sendFile() {

            var file = document.getElementById('filename').files[0];

            var reader = new FileReader();

            var rawData = new ArrayBuffer();            

            reader.loadend = function(e) {

            };

            reader.onload = function(e) {

                var rawData = e.target.result;
                var byteArray = new Uint8Array(rawData);
                var fileByteArray = [];

                webSocket.send(byteArray.buffer);


                echoText.value =("the File has been transferred.\n");

            };

            reader.readAsArrayBuffer(file);

        }

    </script>

</body>

1 个答案:

答案 0 :(得分:1)

最后,我找到了解决方案,所以我发表评论,也许其他人会陷入其中。 我忘记了将布尔参数传递给onMessage函数。 正确的格式是:

print(parser.parse_args())