如何在Java中使用websockets发送图像?

时间:2019-04-14 20:28:26

标签: javascript java jquery spring-websocket java-websocket

我正在尝试通过在“发送消息”区域中拖放来发送图像,但操作失败。我不知道如何在此代码中发送图像。有人可以帮我吗?

ChatEndpoint.java 这是websocket的服务器端点。我有四个方法:onOpen,onClose,onMessage和onError。我在onOpen方法中没有做任何事情。当websocket建立连接时,此方法会被调用。当websocket尝试向客户端发送消息时,onMessage方法被调用。这里从jsp页面(客户端)发送的消息以json字符串格式将其发送到服务器。对象映射器将其转换为java对象。我还为MessageType做了一个枚举,具有两个选项LOGIN和MESSAGE.I检查Java对象是否与登录消息类型匹配,然后根据从会话对象获得的用户属性存储聊天用户的名称,然后还将会话对象发送到join方法中,该方法将会话添加到会话对象列表中还会发送用户已加入聊天室的消息。如果messagetype是消息,则将其发送给会议室类的消息方法,该方法使用sendText将消息发送回客户端。

@ServerEndpoint(value = "/chat")
public class ChatEndpoint {
    private Logger log = Logger.getLogger(ChatEndpoint.class.getSimpleName());
    private Room room = Room.getRoom();

    @OnOpen
    public void onOpen(final Session session, EndpointConfig config) {}

    @OnMessage
    public void onMessage(final Session session, final String messageJson) {
        ObjectMapper mapper = new ObjectMapper();
        ChatMessage chatMessage = null;
        try {
            chatMessage = mapper.readValue(messageJson, ChatMessage.class);
        } catch (IOException e) {
            String message = "Badly formatted message";
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, message));
            } catch (IOException ex) { log.severe(ex.getMessage()); }
        } ;

        Map<String, Object> properties = session.getUserProperties();
        if (chatMessage.getMessageType() == MessageType.LOGIN) {
            String name = chatMessage.getMessage();
            properties.put("name", name);
            room.join(session);
            room.sendMessage(name + " - Joined the chat room");
        }
        else {
            String name = (String)properties.get("name");
            room.sendMessage(name + " - " + chatMessage.getMessage());
        }
    }

    @OnClose
    public void OnClose(Session session, CloseReason reason) {
        room.leave(session);
        room.sendMessage((String)session.getUserProperties().get("name") + " - Left the room");
    }

    @OnError
    public void onError(Session session, Throwable ex) { log.info("Error: " + ex.getMessage()); }


}

Room.java

public class Room {
    private static Room instance = null;
    private List<Session> sessions = new ArrayList<Session>();

    public synchronized void join(Session session) { sessions.add(session); }
    public synchronized void leave(Session session) { sessions.remove(session); }
    public synchronized void sendMessage(String message) {
        for (Session session: sessions) {
            if (session.isOpen()) {
                try { session.getBasicRemote().sendText(message); }
                catch (IOException e) { e.printStackTrace(); }
            }
        }
    }

    public synchronized static Room getRoom() {
        if (instance == null) { instance = new Room(); }
        return instance;
    }
}

index.jsp 在这里,我将发送存储在上下文参数中的wsUri作为ws:// localhost:8080 / single-room-chat / chat

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<% String WsUrl = getServletContext().getInitParameter("WsUrl"); %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name='viewport' content='minimum-scale=1.0, initial-scale=1.0,
    width=device-width, maximum-scale=1.0, user-scalable=no'/>
<title>single-room-chat</title>
<link rel="stylesheet" type="text/css" href="content/styles/site.css">
<script type="text/javascript" src="scripts/chatroom.js"></script>
<script type="text/javascript">
var wsUri = '<%=WsUrl%>';
var proxy = CreateProxy(wsUri);

document.addEventListener("DOMContentLoaded", function(event) {
    console.log(document.getElementById('loginPanel'));
    proxy.initiate({
        loginPanel: document.getElementById('loginPanel'),
        msgPanel: document.getElementById('msgPanel'),
        txtMsg: document.getElementById('txtMsg'),
        txtLogin: document.getElementById('txtLogin'),
        msgContainer: document.getElementById('msgContainer')
    });
});

</script>
</head>
<body>
<div id="container">
    <div id="loginPanel">
        <div id="infoLabel">Type a name to join the room</div>
        <div style="padding: 10px;">
            <input id="txtLogin" type="text" class="loginInput"
                onkeyup="proxy.login_keyup(event)" />
            <button type="button" class="loginInput" onclick="proxy.login()">Login</button>
        </div>
    </div>
    <div id="msgPanel" style="display: none">
        <div id="msgContainer" style="overflow: auto;"></div>
        <div id="msgController">
            <textarea id="txtMsg" 
                title="Enter to send message"
                onkeyup="proxy.sendMessage_keyup(event)"
                style="height: 20px; width: 100%"></textarea>
            <button style="height: 30px; width: 100px" type="button"
                onclick="proxy.logout()">Logout</button>
        </div>
    </div>
</div>
</body>
</html>

chatroom.js

var CreateProxy = function(wsUri) {
    var websocket = null;
    var audio = null;
    var elements = null;

    var playSound = function() {
        if (audio == null) {
            audio = new Audio('content/sounds/beep.wav');
        }

        audio.play();
    };

    var showMsgPanel = function() {
            elements.loginPanel.style.display = "none";
            elements.msgPanel.style.display = "block";
            elements.txtMsg.focus();
    };

    var hideMsgPanel = function() {
            elements.loginPanel.style.display = "block";
            elements.msgPanel.style.display = "none";
            elements.txtLogin.focus();
    };

    var displayMessage = function(msg) {
        if (elements.msgContainer.childNodes.length == 100) {
            elements.msgContainer.removeChild(elements.msgContainer.childNodes[0]);
        }

        var div = document.createElement('div');
        div.className = 'msgrow';
        var textnode = document.createTextNode(msg);
        div.appendChild(textnode); 
        elements.msgContainer.appendChild(div);

        elements.msgContainer.scrollTop = elements.msgContainer.scrollHeight;
    };

    var clearMessage = function() {
        elements.msgContainer.innerHTML = '';
    };

    return {
        login: function() {
            elements.txtLogin.focus();

            var name = elements.txtLogin.value.trim();
            if (name == '') { return; }

            elements.txtLogin.value = '';

            // Initiate the socket and set up the events
            if (websocket == null) {
                websocket = new WebSocket(wsUri);

                websocket.onopen = function() {
                    var message = { messageType: 'LOGIN', message: name };
                    websocket.send(JSON.stringify(message));
                };
                websocket.onmessage = function(e) {
                    displayMessage(e.data);
                    showMsgPanel();
                    playSound();
                };
                websocket.onerror = function(e) {};
                websocket.onclose = function(e) {
                    websocket = null;
                    clearMessage();
                    hideMsgPanel();
                };
            }
        },
        sendMessage: function() {
            elements.txtMsg.focus();

            if (websocket != null && websocket.readyState == 1) {
                var input = elements.txtMsg.value.trim();
                if (input == '') { return; }

                elements.txtMsg.value = '';

                var message = { messageType: 'MESSAGE', message: input };

                // Send a message through the web-socket
                websocket.send(JSON.stringify(message));
            }
        },
        login_keyup: function(e) { if (e.keyCode == 13) { this.login(); } },
        sendMessage_keyup: function(e) { if (e.keyCode == 13) { this.sendMessage(); } },
        logout: function() {
            if (websocket != null && websocket.readyState == 1) { websocket.close();}
        },
        initiate: function(e) {
            elements = e;
            elements.txtLogin.focus();
        }
    }
};

0 个答案:

没有答案