package com.gyee.frame.netty.websocket.secureecho;

import com.gyee.frame.common.conf.EchoConfig;
import com.gyee.frame.common.spring.InitialRunner;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.ByteBuffer;

/**
 * Echo Client.
 *
 */
public final class EchoClient {

	    public  static void runclient( String dateValue) throws Exception {

		String hostName = EchoConfig.echo_ip;
		int portNumber = EchoConfig.echo_port;

		// 配置客户端
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
					.channel(NioSocketChannel.class)
					.option(ChannelOption.TCP_NODELAY, true)
					.handler(new EchoClientChannelInitializer());

			ByteBuffer writeBuffer = ByteBuffer.allocate(32);

			System.out.println("开始"+dateValue);

			// 连接到服务器
			ChannelFuture f = b.connect(hostName, portNumber).sync();

			Channel channel = f.channel();

			writeBuffer.put(dateValue.getBytes());
			writeBuffer.flip();
			writeBuffer.rewind();


			// 转为ByteBuf
			ByteBuf buf = Unpooled.copiedBuffer(writeBuffer);

			// 写消息到管道
			ChannelFuture temp = channel.writeAndFlush(buf);;
			// 清理缓冲区
			writeBuffer.clear();

			while (true)
			{
				Thread.sleep(200);
				if(InitialRunner.status==1)
				{
					InitialRunner.status=0;
					group.shutdownGracefully();

					break;
				}

			}


		} finally {

			// 优雅的关闭
			//group.shutdownGracefully();
		}
	}
}
