2

I'm trying to send a string through netty with a ByteBuf. First of all I convert the string to a byte array like that:

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));

This works well, but I don't know how to read the bytes to convert them back to the string?

I tried something like that:

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

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

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

There must be something to get the bytes back. You can send bytes from a string but can't get the bytes back at the end? Seems like there is a method for that, but I don't have an idea how to do that.

I hope anyone from you can help me. Thanks in advance! :)

2
  • @tima io.netty.buffer.ByteBuf.class != java.nio.ByteBuffer.class Commented Aug 19, 2017 at 8:46
  • @Ferrybig I see now.. Commented Aug 19, 2017 at 12:18

3 Answers 3

3

In netty 4.1 you can use:

byteBuf.writeCharSequence(...)
byteBuf.readCharSequence(...)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Worked perfect :)
This would be a more useful answer if it included a complete example, rather than "..." where the important bits go.
1

How about using Netty's own StringEncoder and StringDecoder ? http://netty.io/4.1/api/io/netty/handler/codec/string/StringEncoder.html

Comments

1

Here is an untested answer:

I assume the data order is correct.

Use this, method "readBytes(ByteBuf dst, int length)" : readBytes

Transmit side change to:

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

Receiving side:

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);

2 Comments

He is writing the .length (length in chars) of the string, this isn't the same as the length in bytes, also, you never initiated the bytesServerName and the bytesIp variables
Thanks, fixed those.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.