【问题标题】:Read and Write strings via ByteBuf using byte[] array使用 byte[] 数组通过 ByteBuf 读取和写入字符串
【发布时间】:2020-05-30 04:00:39
【问题描述】:

我正在尝试通过带有 ByteBuf 的 netty 发送一个字符串。 首先,我将字符串转换为这样的字节数组:

byteBuf.writeInt(this.serverName.length());
byteBuf.writeInt(this.ipAdress.length());

byteBuf.writeBytes(this.serverName.getBytes(StandardCharsets.UTF_8));
byteBuf.writeBytes(this.ipAdress.getBytes(StandardCharsets.UTF_8));

这很好用,但我不知道如何读取字节以将它们转换回字符串?

我尝试过类似的方法:

int snLen = byteBuf.readInt();
int ipLen = byteBuf.readInt();

byte[] bytes = new byte[byteBuf.readableBytes()];

System.out.println(byteBuf.readBytes(bytes).readByte());
this.ipAdress = "";

必须有一些东西来取回字节。您可以从字符串发送字节,但不能在最后取回字节?似乎有一种方法可以做到这一点,但我不知道如何做到这一点。

我希望你们中的任何人都可以帮助我。 提前致谢! :)

【问题讨论】:

  • @tima io.netty.buffer.ByteBuf.class != java.nio.ByteBuffer.class
  • @Ferrybig 我现在看到了..

标签: java netty


【解决方案1】:

在netty 4.1中你可以使用:

byteBuf.writeCharSequence(...)
byteBuf.readCharSequence(...)

【讨论】:

  • 谢谢!工作完美:)
  • 如果它包含一个完整的示例,这将是一个更有用的答案,而不是重要位所在的“...”。
【解决方案2】:

使用 Netty 自己的 StringEncoder 和 StringDecoder 怎么样? http://netty.io/4.1/api/io/netty/handler/codec/string/StringEncoder.html

【讨论】:

    【解决方案3】:

    这是一个未经测试的答案:

    我假设数据顺序是正确的。

    使用这个,方法“readBytes(ByteBuf dst, int length)”:readBytes

    发送端更改到:

    byteBuf.writeInt(this.serverName.getBytes().length);
    byteBuf.writeInt(this.ipAdress.getBytes().length);
    

    接收方:

    int snLen = byteBuf.readInt();
    int ipLen = byteBuf.readInt();
    
    byte[] bytesServerName = new byte[snLen];
    byte[] bytesIp = new byte[ipLen];
    
    byteBuf.readBytes(bytesServerName,snLen);
    byteBuf.readBytes(bytesIp, ipLen);
    
    String serverName  = new String(bytesServerName); 
    String ipAddress   = new String(bytesIp);   
    
    System.out.println(bytesServerName);
    System.out.println(bytesIp);
    

    【讨论】:

    • 他正在编写字符串的.length(字符长度),这与字节长度不同,而且,您从未启动过bytesServerNamebytesIp变量
    • 谢谢,已修复。
    猜你喜欢
    • 1970-01-01
    • 2016-11-04
    • 2016-11-05
    • 2012-07-23
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多