netty echo服务器发送消息,但我没有看到它

时间:2015-09-14 14:23:32

标签: java tcp network-programming client-server netty

我查看了默认手册link,我遇到了问题。我的echo服务器向客户端发送消息,但我没有看到它们。作为一个telnet程序,我使用putty。 代码是一样的:

public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1)

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
    ChannelFuture cf = ctx.write(msg);
    ctx.flush();
    if (!cf.isSuccess()) {
        System.out.println("Send failed: " + cf.cause());
    }else{
        System.out.println("Send worked.");
    }
}

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

第二节课:

public class DiscardServer {

private int port;

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

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync(); // (7)

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

public static void main(String[] args) throws Exception {
    int port;
    if (args.length > 0) {
        port = Integer.parseInt(args[0]);
    } else {
        port = 8080;
    }
    new DiscardServer(port).run();
}
}

cf.isSuccess()是真的,但在控制台(putty)中,我什么也看不见。如果我试图发送文字

ctx.writeAndFlush(Unpooled.copiedBuffer("Netty MAY rock!", CharsetUtil.UTF_8));
  • 它有效。但如果我试图发送&#34; msg&#34; - 我一无所获。 在此先感谢您的回复。

2 个答案:

答案 0 :(得分:1)

要读取和写入非ByteBuf消息,您需要解码器和编码器。

ch.pipeline().addLast(new LineBasedFrameDecoder(80))
                    .addLast(new StringDecoder())
                    .addLast(new StringEncoder())
                    .addLast(new DiscardServerHandler());

或者您可以手动解码和编码消息。将String编码为ByteBuf

ctx.writeAndFlush(Unpooled.copiedBuffer("Netty MAY rock!", CharsetUtil.UTF_8));

答案 1 :(得分:0)

您在此处提到的相同代码正在按原样运行。测试了它。