使用 byte[] 数组通过 ByteBuf 读写字符串

Read and Write strings via ByteBuf using byte[] array

我正在尝试使用 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 = "";

一定有什么东西可以取回字节。您可以从字符串发送字节,但最后无法取回字节?似乎有一种方法,但我不知道该怎么做。

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

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

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

使用这个方法 "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);

在 netty 4.1 中你可以使用:

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

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