我正在尝试使用Websocket。我不知道Java的onMessage方法是否使用javascript。如何使用javascript函数?

时间:2019-01-03 02:41:21

标签: java websocket

我不知道Java onMessage方法的JavaScript。如何使用javascript函数?

我尝试使用ajaxjson发送数据。

我希望控制台查看System.out.println(message)方法的onMessage

broadcast.html

    var textarea = document.getElementById("messageWindow");
    var webSocket = new WebSocket('ws://localhost:8888/hanyoung/broadcasting');
    var inputMessage = document.getElementById('inputMessage');
    webSocket.onerror = function(event) {
      onError(event)
    };

    webSocket.onopen = function(event) {
      onOpen(event)
    };

    webSocket.onmessage = function(event) {
      onMessage(event)
    };

    function onMessage(event) {
        textarea.value += "상대 : " + event.data + "\n";
    }

    function onOpen(event) {
        textarea.value += "연결 성공\n";
    }

    function onError(event) {
      alert(event.data);
    }

    function send() {
        textarea.value += "나 : " + inputMessage.value + "\n";
        webSocket.send(inputMessage.value);
        inputMessage.value = "";
    }

Broadsocket.java

public class Broadsocket {
    private static Set<Session> clients = Collections
        .synchronizedSet(new HashSet<Session>());

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println(message);
        synchronized (clients) {
            // Iterate over the connected sessions
            // and broadcast the received message
            for (Session client : clients) {
                if (!client.equals(session)) {
                    client.getBasicRemote().sendText(message);
                }
            }
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        // Add session to the connected sessions set
        System.out.println(session);
        clients.add(session);
    }

    @OnClose
    public void onClose(Session session) {
        // Remove session from the connected sessions set
        clients.remove(session);
    }
}

0 个答案:

没有答案