package com.jpsoft.shinestar.lapi;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import java.net.URI;

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

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new HttpRequestEncoder());//客户端对发送的httpRequest进行编码
                            socketChannel.pipeline().addLast(new HttpResponseDecoder());//客户端需要对服务端返回的httpresopnse解码
                            // socketChannel.pipeline().addLast(new HttpClientCodec());//HttpClientCodec()包含了上面两种
                            socketChannel.pipeline().addLast(new HttpClientDealing());
                        }
                    });
            try {
                Channel channel = bootstrap.connect("127.0.0.1", 8080).sync().channel();

                URI uri = new URI("http://127.0.0.1:8080");
                DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());//生成一个默认的httpRequest。

                channel.writeAndFlush(httpRequest).sync();//发送

                channel.closeFuture().sync();
            }
            catch (Exception ex){
                ex.printStackTrace();
            }
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
