如何打开与netty的连接,并立即将数据发送到我连接的主机?

时间:2017-01-14 06:53:50

标签: java netty

我试图找出如何打开与netty的连接并向服务器发送一些数据。

这是我试图开始工作的代码:

public static void main(String[] args) {
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap(); // (1)
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new InboundHandler());
                ch.pipeline().addLast(new OutboundHandler());
            }
        });


        Channel channel = b.connect("localhost", 22000).channel();
        channel.write(true); //Lets send a boolean to test. 

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

我的inboundhandler注册时,我也尝试过发送数据。不确定我做错了什么。

1 个答案:

答案 0 :(得分:2)

向管道添加日志记录处理程序以调试数据交换:

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ch.pipeline().addFirst(new LoggingHandler(LogLevel.INFO));
    ch.pipeline().addLast(new InboundHandler());
    ch.pipeline().addLast(new OutboundHandler());
}

您应该添加侦听器以响应连接完成事件,如下所示:

ChannelFuture cf = b.connect("localhost", 22000);

cf.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
        if(future.isSuccess()) {
            //Here wrap your data into ByteBuf
            future.channel().writeAndFlush(Unpooled.buffer().writeByte(5));
        } else {
            //Connection failed, add proper error handling !
            future.cause().printStackTrace(System.err);
        }
    }
});

确认已收到数据:

strace -e recvfrom nc -k -l 22000

09:16:18.222252 recvfrom(5, "\x05", 8192, 0, NULL, NULL) = 1
09:16:18.223916 recvfrom(5, "", 8192, 0, NULL, NULL) = 0