Java Websocket client lib issue: nv-websocket-client sendBin



当从客户端使用此库的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:

非常感谢您的帮助。

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

相关内容

  • 没有找到相关文章

最新更新