I have a Netty Client and a Netty Server, and after following the main tutorials in order to have an EchoClient / Server I wanted to make it so that my Client sends a message to my Server when he first connects to it.
Here are my ClientClassHandler
's methods that should take care of that:
private final ByteBuf firstMessage;
public ClientClassHandler() {
firstMessage = Unpooled.buffer(ClientClass.SIZE);
for (int i = 0; i < firstMessage.capacity(); i++) {
firstMessage.writeByte((byte) i);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("Channel is active.");
ctx.writeAndFlush(firstMessage);
}
But as you can see the tutorial uses a ByteBuf
and the use of a String
does not seem to work !
Here is how I display my received message in my ServerClassHandler
's method:
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println(msg);
}
But when using a String
for firstMessage
and initializing it in the constructor and sending it, my Server does not display anything !
What did I not understand?
If you want to send a String then convert it into a ByteBuf first using Unpooled.copiedBuffer(string, charset)
Netty has a CharsetUtil to help with this
Just want add more info about String in netty ,
you can do convert Object into Bytebuff
ByteBuf in = (ByteBuf) msg;
String data = in.toString(CharsetUtil.UTF_8);
But if you have long String object I suggest using StringEncoder and decoder for netty and LineBasedFrameDecoder and extends you handler to
SimpleChannelInboundHandler<String>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.