如何创建一个简单的Netty客户端,该客户端在启动时发送请求

时间:2019-06-03 13:54:29

标签: client netty

我正在开发一个使用Netty 4.1.9的项目。我正在尝试构建一个非常简单的HTTP客户端,该客户端将请求发送到主机,等待响应,然后退出。

我正在使用netcat调试该程序,但是当我运行它时,该进程将阻塞并且从不实际发送请求。下面是我的HttpClient类:

public class HttpClient {
    private String uri;
    private int port;
    private String payload;

    public HttpClient(String uri, int port, String payload) {
        this.uri = uri;
        this.port = port;
        this.payload = payload;
    }

    public void run() throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new HttpClientCodec());
                    ch.pipeline().addLast(new HttpObjectAggregator(1048576));
                    ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
                            final String echo = msg.content().toString(CharsetUtil.UTF_8);
                            System.out.println(echo);
                        }
                    });
                    ch.pipeline().addLast(new HttpRequestEncoder());
                }
            });

            HttpRequest request = HttpRequester.createRequest(this.uri, this.payload);
            request.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
            System.out.println("Sending message!");
            Channel f = b.connect(uri, port).sync().channel();
            f.writeAndFlush(request);
            f.closeFuture().sync();
            System.out.println("Message was sent!");
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}

运行此命令时,将打印“正在发送消息”日志,但从不打印“消息已发送”。另外,netcat显示该进程的连接已被接受,但从不显示该消息。

0 个答案:

没有答案