Netty channelRead没有调用

时间:2015-03-27 16:46:04

标签: java netty

我试图让多个Netty客户端相互通信。我在尝试这个时遇到了一个问题。当我写信道时,它不会拨打NettyClientHandler#channelRead

NettyClient上课:

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上课:

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

NettyClientInitializer上课:

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());
    }
}

1 个答案:

答案 0 :(得分:1)

您需要替换:

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

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