如何从javascript客户端onmessage函数

时间:2016-02-13 09:41:44

标签: javascript java websocket

java中的服务器代码:

@OnMessage
public void onMessage(Session session, ByteBuffer message) {
    if (session.isOpen()) {
        String msg = new String(message.array());
        System.out.println("Message from " + session.getId() + ": " + msg);
        try {
           session.getBasicRemote().sendBinary(ByteBuffer.wrap("I have got the message".getBytes()));
        } catch (IOException ioe) {
            System.out.println(ioe.toString());
        }
    } else {
        System.out.println("Session is not open");
    }
}

Javascript中的客户端代码:

    webSocket = new WebSocket("ws://192.168.10.1:2525/myChat/chat");
    webSocket.binaryType = 'arraybuffer';
    webSocket.onopen = function(event) {
        updateOutput("Connected!");
        connectBtn.disabled = true;
        sendBtn.disabled = false;
    };

    webSocket.onmessage = function(event) {
        updateOutput(event.data);
    };

注意:   当我将它与Web GL客户端一起使用时,服务器代码工作正常,因为它发送二进制数据。   当我在服务器端读取字符串数据时,Javascript客户端工作正常   (来自java代码):

@OnMessage
public void onMessage(Session session, String message) {}

感谢任何意见的建议。

1 个答案:

答案 0 :(得分:0)

我找到了问题的解决方案。

我使用ByteBuffer.js库在JavaScript中发送/读取ByteBuffer类型的数据:

webSocket.binaryType =" arraybuffer&#34 ;;

在函数onmessage中读取数据:

var d = event.data; 的console.log(d.toString());

在发送数据的函数中发送:

var bb = dcodeIO.ByteBuffer.wrap(text); webSocket.send(bb.toArrayBiffer());