Reputation: 13
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! :)
Upvotes: 1
Views: 5332
Reputation: 3519
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);
Upvotes: 1
Reputation: 16056
How about using Netty's own StringEncoder and StringDecoder ? http://netty.io/4.1/api/io/netty/handler/codec/string/StringEncoder.html
Upvotes: 1
Reputation: 23557
In netty 4.1 you can use:
byteBuf.writeCharSequence(...)
byteBuf.readCharSequence(...)
Upvotes: 2