简单Netty Echo服务器/客户端无法接收消息

时间:2014-09-08 09:12:03

标签: java tcp client-server netty

我正在尝试用Netty编写一个简单的echo服务器。我正在阅读Netty in Action MEAP v8以了解一些理论并学习Netty的核心基础知识。客户端连接成功,但客户端没有消息通过。我能够将一条消息telnet到服务器并收到响应,所以我想问题是在客户端上,我不知道出了什么问题,因为我是Netty的新手。

这是客户:

public class Client {

    private final String host;
    private final int port;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                          .remoteAddress(new InetSocketAddress(host, port))
                          .handler(new ChannelInitializer<SocketChannel>() {

                              @Override
                              public void initChannel(SocketChannel ch) throws Exception {
                                  ch.pipeline().addLast(new EchoClientHandler());
                              }
                          });

            ChannelFuture f = b.connect().sync();

            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }


    public static void main (String [] args) throws Exception {
        new Client("127.0.0.1", 11235).start();
    }
}

和客户端处理程序:(我确实尝试将'\ r \ n'添加到已发送的消息中,但这没有什么区别,我在此处找到:Netty Client to Server message

@Sharable 
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("Connected");
        ctx.write(Unpooled.copiedBuffer("Netty MAY rock!", CharsetUtil.UTF_8));
    }

    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        System.out.println(
                "Client received: " + in.toString(CharsetUtil.UTF_8));

    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

服务器:

public class EchoServer {

    private final int port;

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

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                                    @Override
                                    public void initChannel(SocketChannel ch) throws Exception {
                                        System.out.println("New client connected: " + ch.localAddress());

                                        ch.pipeline().addLast(new EchoServerHandler());
                                    }
                                });
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main (String [] args) throws Exception {
        new EchoServer(11235).start();
    }
}

服务器处理程序:

@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        System.out.println(
            "Server received: " + in.toString(CharsetUtil.UTF_8));
        ctx.write(in);
    }

    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
            .addListener(ChannelFutureListener.CLOSE);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

它一定是我失踪的小东西,所以任何帮助都会保持我的短暂理智,非常感谢!

1 个答案:

答案 0 :(得分:6)

而不是write在ClientHandler中使用writeAndFlush

public void channelActive(ChannelHandlerContext ctx) {
    System.out.println("Connected");
    ctx.writeAndFlush(Unpooled.copiedBuffer("Netty MAY rock!", CharsetUtil.UTF_8));
}