Netty channel.write does not write a message

I am trying to take the first steps with Netty, for this I wrote a simple server on Netty and a simple client on oio plain TCP.

The client sends a random text packet and should receive a "ack" message. See Handler Method:

@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.write("Ack"); ctx.flush(); ByteBuf in = (ByteBuf) msg; StringBuilder sb = new StringBuilder(); try { while (in.isReadable()) { sb.append((char) in.readByte()); } } finally { ReferenceCountUtil.release(msg); } LOG.debug("Incoming message. ACK was send"); String myaddr = ctx.channel().remoteAddress().toString(); String message = "Message from " + myaddr + " :" + sb.toString(); LOG.debug(message); sendToOther(myaddr, message); } 

The problem is - when I try to send the string "Ack" back - the client does not receive anything. But when I try to send an incoming message back - it works fine, and I see an echo in my client.

  @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.write(msg); ctx.flush(); 

write () needs an Object, and I tried to send (Object) String - but nothing happened. I also tried sending ByteBuf (I saw this in one article) and it still doesn't work.

When I send an incoming message as an echo, it works. When I post what else - it is not. Please help me, I just can’t understand where my mistake is.


I solved this problem. The thing was that you only had to send ByteBuff. Therefore, we need to create it and write something, and only then can we record it in the chanel channel. in my case it was like:

 String ack = "ACK"; ByteBuf out = ctx.alloc().buffer(ack.length()*2); out.writeBytes(ack.getBytes()); ctx.write(out); ctx.flush(); LOG.debug("Incoming message. ACK was send"); 

This may not be an exceptional solution, but it works as an example.

+5
source share
1 answer

You will see why this fails if you replace

 ctx.write("Ack"); ctx.flush(); 

in your Handler server with the following:

 ChannelFuture cf = ctx.write("Ack"); ctx.flush(); if (!cf.isSuccess()) { System.out.println("Send failed: " + cf.cause()); } 

It should give you a message that String not supported.

ByteBuf should work:

 ctx.write(Unpooled.copiedBuffer("Ack", CharsetUtil.UTF_8)); ctx.flush(); 

on the client side, edit the channelRead method:

 ByteBuf in = (ByteBuf) msg; System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8)); 
+16
source

Source: https://habr.com/ru/post/1202220/


All Articles