当从客户端使用此lib的sendBinary时,我在服务器中得到全部0;(
这个页面要求我添加更多描述,但下面的代码简单明了,应该可以自我解释......
客户端代码:
private WebSocket connect() throws IOException, WebSocketException {
return new WebSocketFactory()
.setConnectionTimeout(5000)
.createSocket("ws://localhost:8080/testwsapp2/endpoint")
.addListener(new WebSocketAdapter() {
public void onBinaryMessage(WebSocket websocket, byte[] message) {
String strmsg = new String(message, StandardCharsets.US_ASCII);
System.out.println("message from server: " + strmsg);
//echo back
try {
strmsg = "echo: " + strmsg;
System.out.println("now echo back with \"" + strmsg + "\"");
byte[] bytemsg = strmsg.getBytes("US-ASCII");
System.out.println("echo message length = " + bytemsg.length);
String a2sview = Arrays.toString(bytemsg);
System.out.println("echo message a2sview: " + a2sview);
websocket.sendBinary(bytemsg);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
})
.addExtension(WebSocketExtension.PERMESSAGE_DEFLATE)
.connect();
}
服务器端代码:
@OnOpen
public void on_open(Session session) {
try {
byte[] bytemsg = ("hello client").getBytes("US-ASCII");
session.getBasicRemote().sendBinary(ByteBuffer.wrap(bytemsg));
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
@OnMessage
public void on_message(Session session, ByteBuffer message) {
byte[] bytemsg = new byte[message.remaining()];
System.out.println("client message length = " + bytemsg.length);
String a2sview = Arrays.toString(bytemsg);
System.out.println("client message a2sview: " + a2sview);
String strmsg = new String(bytemsg, StandardCharsets.US_ASCII);
System.out.println("client message: " + strmsg);
}
客户输出:
message from server: hello client
now echo back with "echo: hello client"
echo message length = 18
echo message a2sview: [101, 99, 104, 111, 58, 32, 104, 101, 108, 108, 111, 32, 99, 108, 105, 101, 110, 116]
服务器输出
Info: client message length = 18
Info: client message a2sview: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Info: client message:
非常感谢您的帮助。
答案 0 :(得分:0)
在服务器端on_message
方法中,在将message
传递给bytemsg
之前,您必须将bytemsg
的内容复制到Array.toString
。
byte[] bytemsg = new byte[message.remaining()];
System.out.println("client message length = " + bytemsg.length);
// !!! Copy the content of 'message' to 'bytemsg' here !!!
String a2sview = Arrays.toString(bytemsg);
System.out.println("client message a2sview: " + a2sview);