2

I am new to Netty and I am trying to write a client functionality, to send dynamic messages using direct buffer. Below is code snippet I am currently using, is byteBuf.copy() "channel.writeAndFlush(byteBuf.copy())" the correct way of passing the contents of direct buffer to SocketChannel, from performance perspective. If I don't use copy(), the value of i passed to channel gets overwritten. Please help.

Sample Client Code
------------------
public class Sample {
final ByteBuf byteBuf= PooledByteBufAllocator.DEFAULT.directBuffer(1024, 1024);
final MessageChannel CHANNEL = new MessageChannel(new InetSocketAddress( "0.0.0.0", 1111));
    public static void main(final String[] args) throws Exception {
        for (int i =0; i<=10; i++) {
            byteBuf.writerIndex(0);
            byteBuf.writeInt(i);
            CHANNEL.sendMsg(byteBuf);
        }
    }
}

Netty Client
------------
public class MessageChannel {
    private Channel channel;
    ThreadFactory workerThreadFactory = new DefaultThreadFactory("NettyClient/worker");
    private EventLoopGroup eventLoopGroup = new NioEventLoopGroup(workerThreadFactory);

    public MessageChannel(InetSocketAddress inetSocketAddress) {
        try {
            channel = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.TCP_NODELAY, true)
                .remoteAddress(inetSocketAddress)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new MessageDecoder(), new InboundHandler());
                    }
                }).connect().sync().channel();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void shutdownChannel() {
        eventLoopGroup.shutdownGracefully();
    }

    public void sendMsg(ByteBuf byteBuf) throws InterruptedException {
        channel.writeAndFlush(byteBuf.copy());
    }
}
Shankar
  • 21
  • 2

0 Answers0