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) {}
感谢任何意见的建议。
最佳答案
我已经找到了问题的解决方案。
我使用 ByteBuffer.js 库在 JavaScript 中发送/读取 ByteBuffer 类型的数据:
webSocket.binaryType = "arraybuffer";
在onmessage函数中读取数据:
var d = event.data;
console.log(d.toString());
在send函数中发送数据:
var bb = dcodeIO.ByteBuffer.wrap(text);
webSocket.send(bb.toArrayBiffer());
关于javascript - 如何从 javascript 客户端 onmessage 函数发送/读取 java ByteBuffer (websocket),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35378316/