package com.pwt.netty.client;

import com.pwt.netty.handler.Vehicle2ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @author linyun
 * @version V1.0
 * @Title: Vehicle2Client
 * @Description: netty客户端
 * @date 2022/11/03
 **/
@Component
public class Vehicle2Client {

    public static void main(String[] args) throws InterruptedException
    {
        Vehicle2Client client = new Vehicle2Client();
        client.start("127.0.0.1", 3000);
    }

    /**
     * @Description: 客户端启动方法
     * @Author: linyun
     * @Date: 2022/11/3 9:40
     * @Param:[host ip地址, port 端口, payload 数据]
     * @Return:void
     **/
    public static void start(String host, int port) throws InterruptedException
    {

        /**
         * Netty用于接收客户端请求的线程池职责如下。
         * （1）接收客户端TCP连接，初始化Channel参数；
         * （2）将链路状态变更事件通知给ChannelPipeline
         */
        NioEventLoopGroup group = new NioEventLoopGroup();
        try
        {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception
                        {
                            ChannelPipeline p = sc.pipeline();
                            p.addLast(new IdleStateHandler(1, 0, 0, TimeUnit.SECONDS));
                            p.addLast(new Vehicle2ClientHandler());
                        }
                    });
            // 绑定端口
            ChannelFuture sync = b.connect().sync();
            // 发送消息
            // sync.channel().writeAndFlush(payload);
            // System.out.println("消息发送完成");
            // 关闭连接
            // sync.channel().close();

            // 异步等待关闭连接channel
            // sync.channel().closeFuture().sync();
        } catch (Exception e)
        {
            group.shutdownGracefully().sync();
        } finally
        {
//            group.shutdownGracefully();
        }
    }
}
