Java 使用byte[]数组通过ByteBuf读取和写入字符串

Java 使用byte[]数组通过ByteBuf读取和写入字符串,java,netty,Java,Netty,我正试着用一个便签把一根绳子穿过内蒂。 首先,我将字符串转换为字节数组,如下所示: byteBuf.writeInt(this.serverName.length()); byteBuf.writeInt(this.ipAdress.length()); byteBuf.writeBytes(this.serverName.getBytes(StandardCharsets.UTF_8)); byteBuf.writeBytes(this.ipAdress.getBytes(StandardC

我正试着用一个便签把一根绳子穿过内蒂。 首先,我将字符串转换为字节数组,如下所示:

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 = "";
这很好,但我不知道如何读取字节以将其转换回字符串

我试过这样的方法:

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)”:

将侧面变更发送至:

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怎么样

谢谢!工作完美:)如果包含完整的示例,这将是一个更有用的答案,而不是“…”重要位的位置。他正在编写字符串的
.length
(字符长度),这与字节长度也不同,您从未启动过
bytesServerName
bytesIp
variablesThanks,修复了这些问题。@tima
io.netty.buffer.ByteBuf.class!=java.nio.ByteBuffer.class
@Ferrybig我现在明白了。。