package com.platform.modules.fl.utils;

import org.tio.client.AioClient;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Aio;
import org.tio.core.Node;

/**
 *
 * @author tanyaowu
 *
 */
public class ClientStarter {
	//服务器节点
	public static Node serverNode = new Node("127.0.0.1",9001);

	public static ClientAioHandler aioClientHandler = new FrontendClientAioHandler();

	//事件监听器，可以为null，但建议自己实现该接口，可以参考showcase了解些接口
	public static ClientAioListener aioListener = null;

	//断链后自动连接的，不想自动连接请设为null
	private static ReconnConf reconnConf = new ReconnConf(5000L);

	//一组连接共用的上下文对象
	public static ClientGroupContext clientGroupContext = new ClientGroupContext(aioClientHandler, aioListener, reconnConf);

	public static AioClient aioClient = null;
	public static ClientChannelContext clientChannelContext = null;

	/**
	 * 启动程序入口
	 */
	public static void main(String[] args) throws Exception {
		clientGroupContext.setHeartbeatTimeout(0);
		aioClient = new AioClient(clientGroupContext);
		clientChannelContext = aioClient.connect(serverNode);
		System.out.println(clientChannelContext.getReconnCount());
		 
		//连上后，发条消息玩玩
		send();
		//aioClient.stop();
	}

	private static void send() throws Exception {
		SendPacket packet = new SendPacket();
		String test= "" + 
				"<?xml version='1.0' encoding='GB2312' ?>" + 
				"<COMMAND_INFO AREA_ID=\"3709110003\"  CHNL_NO=\"3709030001\"  I_E_TYPE=\"E\">				         <RESULT>0</RESULT>						 <USER_ID></USER_ID> 						 <RIGHTS>2</RIGHTS>						 <USERNAME></USERNAME> 						 <UNIT></UNIT> 						 <CUSTOMS_NO></CUSTOMS_NO> 						 <PIC_DATA_FLAG>0</PIC_DATA_FLAG>						 <VEHICLE_DATA_FLAG>0</VEHICLE_DATA_FLAG>						 <WEIGHT_DATA_FLAG>0</WEIGHT_DATA_FLAG>						 <IC_DATA_FLAG>0</IC_DATA_FLAG>						 <SEAL_DATA_FLAG>0</SEAL_DATA_FLAG>						 <GPS_DATA_FLAG>0</GPS_DATA_FLAG>						 <CHNL_TYPE>0</CHNL_TYPE>						 <BUSI_TYPE>01</BUSI_TYPE>						 </COMMAND_INFO>" + 
				"";
		packet.setBody(hex2byte(test));
		Aio.send(clientChannelContext, packet);
	}
	public static byte[] hex2byte(String hex) {
        String digital = "0123456789ABCDEF";
        String hex1 = hex.replace(" ", "");
        char[] hex2char = hex1.toCharArray();
        byte[] bytes = new byte[hex1.length() / 2];
        byte temp;
        for (int p = 0; p < bytes.length; p++) {
            temp = (byte) (digital.indexOf(hex2char[2 * p]) * 16);
            temp += digital.indexOf(hex2char[2 * p + 1]);
            bytes[p] = (byte) (temp & 0xff);
        }
        return bytes;
    }
}










