package com.persagy.socket;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @version 1.0.0
 * @company persagy
 * @author zhangqiankun
 * @date 2021年10月12日 上午10:06:34
 */
@Slf4j
public class IotSocketClient {
	
	public static boolean connectAndSend(String host, int port, String command) {
		EventLoopGroup group = new NioEventLoopGroup(1);
		Bootstrap bs = new Bootstrap();
		// 注册线程池、使用NioSocketChannel来作为连接用的channel类
		bs.group(group).channel(NioSocketChannel.class);
		
		boolean result = false;
		ChannelFuture cf = null;
		try {
			bs.remoteAddress(new InetSocketAddress(host, port)) // 绑定连接端口和host信息
				.handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						log.info("正在连接中...");
						ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
						ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
						ch.pipeline().addLast(new IotClientHandler(command));
					}
				});

			cf = bs.connect().sync(); // 异步连接服务器
			log.info("服务端连接成功...");
			
			result = true;
		} catch (Exception e) {
			log.error("与服务端建立连接失败", e);
		} finally {
			if (cf != null) {
				try {
					cf.channel().closeFuture().sync();
					log.info("连接已关闭..");
				} catch (Exception e2) {
					log.error("未知异常", e2);
				}
			}
			if (group != null) {
				group.shutdownGracefully();
				log.info("线程池已关闭..");
			}
		}
		
		return result;
	}

	public static void main(String[] args) throws Exception {
		IotSocketClient.connectAndSend("192.168.100.102", 30054, "(5001120003;1;report;20220617100000;17107;ZD1060;1;902;155)");
	}
	
}
