gpt4 book ai didi

Java Websocket 客户端库问题 : nv-websocket-client sendBinary

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:18 25 4
gpt4 key购买 nike

当从客户端使用此库的 sendBinary 时,我在服务器中得到的全是 0 ;(

此页面要求我添加更多描述,但下面的代码简单明了,应该可以 self 解释......

客户端代码:

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:

非常感谢您的帮助。

最佳答案

在服务器端 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);

关于Java Websocket 客户端库问题 : nv-websocket-client sendBinary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35353328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com