XLordalX
XLordalX

Reputation: 594

Netty channelRead not called

I'm trying to make multiple Netty clients communicate with each other. I encountered a problem while trying this. When I write to a channel it does not call NettyClientHandler#channelRead.

NettyClient class:

public class NettyClient
{
    private static NettyClient client;
    private int port;
    private Channel channel;

    public NettyClient(int port)
    {
        this.port = port;
    }

    public static void start(final int port)
    {
        BungeeCord.getInstance().getScheduler().runAsync(AzideaCord.getInstance(), new Runnable()
        {
            @Override
            public void run()
            {
                client = new NettyClient(port);
                client.run();
            }
        });
    }

    private void run()
    {
        EventLoopGroup group = new NioEventLoopGroup();

        try
        {
            Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientInitializer());

            channel = bootstrap.bind(port).sync().channel();
            System.out.println("[Netty] Connected to localhost:" + port + ".");
            channel.write("test" + "\r\n");
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
        finally
        {
            group.shutdownGracefully();
        }
    }
}

NettyClientHandler class:

public class NettyClientHandler extends ChannelInboundHandlerAdapter
{
    // Never called
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        System.out.println("Msg: " + msg); 
    }
}

NettyClientInitializer class:

public class NettyClientInitializer extends ChannelInitializer<SocketChannel>
{
    @Override
    protected void initChannel(SocketChannel channel) throws Exception
    {
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new StringEncoder());
        pipeline.addLast(new NettyClientHandler());
    }
}

Upvotes: 1

Views: 2471

Answers (1)

Norman Maurer
Norman Maurer

Reputation: 23557

You need to replace:

channel.write("test" + "\r\n");

channel.writeAndFlush("test" + "\r\n");

Upvotes: 1

Related Questions