通道处理程序没有在netty 4.0上写消息

时间:2014-06-17 08:18:03

标签: netty

我写了这样简单的ChannelHandler。

public class SimpleServerHandler extends SimpleChannelInboundHandler<Object> {

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
    ctx.write("It is " + new Date() + " now.\r\n");
    ctx.flush();
}

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.writeAndFlush("=>complete");
    System.out.println("complete");
};

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    // Close the connection when an exception is raised.
    cause.printStackTrace();
    ctx.close();
}

}

如果客户端(telnet)连接到服务器,此处理程序将显示欢迎消息。如果阅读完成,则显示完整的消息。 我尝试连接服务器但服务器的任何消息响应(但我确认了系统日志)。

我无法理解为什么。

P.S:我附上引导服务器的代码

public class SimpleServer {

public static void main(String... args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new SimpleServerHandler());
            }
        });
        b.option(ChannelOption.SO_BACKLOG, 128);
        b.childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind("127.0.0.1", 8080).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

}

1 个答案:

答案 0 :(得分:0)

在编写String时,需要在ChannelPipeline中放置StringEncoder。如果将ChannelFutureListener添加到write(...)返回的ChannelFuture,您将看到错误。