org.apache.mina.filter.logging.LoggingFilter Java Examples

The following examples show how to use org.apache.mina.filter.logging.LoggingFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CIMNioSocketAcceptor.java    From cim with Apache License 2.0 6 votes vote down vote up
private void bindWebPort() throws IOException {

		/*
		 * 预制websocket握手请求的处理
		 */
		INNER_HANDLER_MAP.put(CIMConstant.CLIENT_WEBSOCKET_HANDSHAKE, new WebsocketHandler());

		webAcceptor = new NioSocketAcceptor();
		((DefaultSocketSessionConfig) webAcceptor.getSessionConfig()).setKeepAlive(true);
		((DefaultSocketSessionConfig) webAcceptor.getSessionConfig()).setTcpNoDelay(true);
		webAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new WebMessageCodecFactory()));
		webAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
		webAcceptor.getFilterChain().addLast("executor", new ExecutorFilter(createWorkerExecutor()));
		webAcceptor.setHandler(this);

		webAcceptor.bind(new InetSocketAddress(webPort));
		String logBanner = "\n\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"*                   Websocket Server started on port {}.                         *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
		LOGGER.info(logBanner, webPort);
	}
 
Example #2
Source File: MinaTimeServer.java    From frameworkAggregate with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {

		IoAcceptor acceptor = new NioSocketAcceptor();
		// 这个过滤器用来记录所有的信息,比如创建session(会话),接收消息,发送消息,关闭会话等
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		// 用来转换二进制或协议的专用数据到消息对象中
		acceptor.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

		// 实时处理客户端的连接和请求
		acceptor.setHandler(new TimeServerHandler());
		acceptor.getSessionConfig().setReadBufferSize(2048);
		// 方法将定时调用一次会话,保持空闲状态。来设定时间间隔。
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		acceptor.bind(new InetSocketAddress(PORT));
	}
 
Example #3
Source File: ArduinoDevice.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public synchronized void start ()
{
    if ( this.started )
    {
        return;
    }

    this.started = true;

    this.executorService = ScheduledExportedExecutorService.newSingleThreadExportedScheduledExecutor ( "ArduninoDevice/" + this.address );

    this.connector = new NioDatagramConnector ();

    this.connector.setHandler ( this );
    if ( this.activateLogger )
    {
        this.connector.getFilterChain ().addLast ( "logger", new LoggingFilter ( this.getClass ().getName () ) );
    }

    final ArduinoCodec codec = new ArduinoCodec ();
    this.connector.getFilterChain ().addLast ( "codec", new ProtocolCodecFilter ( codec, codec ) );

    this.connector.connect ( this.address );
}
 
Example #4
Source File: HelloTcpClient.java    From mina-examples with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	NioSocketConnector connector = new NioSocketConnector(); //TCP Connector
	connector.getFilterChain().addLast("logging", new LoggingFilter());
	connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
    connector.getFilterChain().addLast("mdc", new MdcInjectionFilter());
	connector.setHandler(new HelloClientHandler());
    IoSession session;

    for (;;) {
        try {
            ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT));
            future.awaitUninterruptibly();
            session = future.getSession();
            break;
        } catch (RuntimeIoException e) {
            System.err.println("Failed to connect.");
            e.printStackTrace();
        }
    }
    session.getCloseFuture().awaitUninterruptibly();
    connector.dispose();
}
 
Example #5
Source File: ModbusMaster.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void configureConnector ( final NioSocketConnector connector )
{
    logger.debug ( "Configuring connector: {}", connector );

    switch ( this.protocolType )
    {
        case TYPE_TCP:
            connector.getFilterChain ().addLast ( "modbusPdu", new ProtocolCodecFilter ( new ModbusTcpEncoder (), new ModbusTcpDecoder () ) );
            connector.getFilterChain ().addLast ( "modbus", new ModbusMasterProtocolFilter () );
            break;
        case TYPE_RTU:
            // convert milliseconds to microseconds to allow more accurate timing
            final ModbusRtuDecoder rtuDecoder = new ModbusRtuDecoder ( getExecutor (), Double.valueOf ( this.interFrameDelay * 1000 ).longValue (), TimeUnit.MICROSECONDS );
            connector.getFilterChain ().addLast ( "modbusPdu", new ModbusRtuProtocolCodecFilter ( new ModbusRtuEncoder (), rtuDecoder ) );
            connector.getFilterChain ().addLast ( "modbus", new ModbusMasterProtocolFilter () );
            break;
        default:
            throw new IllegalArgumentException ( String.format ( "'%s' is not an allowed modbus device type", this.protocolType ) );
    }

    if ( Boolean.getBoolean ( "org.eclipse.scada.da.server.osgi.modbus.trace" ) )
    {
        connector.getFilterChain ().addFirst ( "logger", new LoggingFilter ( ModbusMaster.class.getName () + ".protocol" ) );
    }
}
 
Example #6
Source File: MinaTimeServer.java    From java-tutorial with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    // 创建服务器端的监听器对象
    IoAcceptor acceptor = new NioSocketAcceptor();
    // 增加日志过滤器:用于日志存储
    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    // 增加消息编码过滤器,采用UTF-8编码
    acceptor.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
    // 设置具体的事物逻辑处理器
    acceptor.setHandler(new TimeServerHandler());
    // 设置IoSession的一些属性
    acceptor.getSessionConfig().setReadBufferSize(2048);
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
    // 设置服务器监听的端口
    acceptor.bind(new InetSocketAddress(PORT));
}
 
Example #7
Source File: CalculatorServer.java    From mina with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
        IoAcceptor acceptor = new NioSocketAcceptor();
//        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, IDELTIMEOUT);

        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.getFilterChain().addLast("myfliter", new MyFilter());
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CommandCodecFactory("UTF-8")));

        KeepAliveMessageFactoryImpl kamfi = new KeepAliveMessageFactoryImpl();
        KeepAliveFilter kaf = new KeepAliveFilter(kamfi, IdleStatus.BOTH_IDLE);
        /** 是否回发 */
        kaf.setForwardEvent(true);
        acceptor.getFilterChain().addLast("heart", kaf);

        acceptor.setHandler(new CalculatorHandler());
        acceptor.bind(new InetSocketAddress(PORT));

        log.debug("socket通信服务端已启动,端口是" + PORT);
    }
 
Example #8
Source File: MimaTimeClient.java    From frameworkAggregate with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	IoConnector connector = new NioSocketConnector();
	connector.getFilterChain().addLast("logger", new LoggingFilter());
	connector.getFilterChain().addLast("codec",
			new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset.forName("UTF-8"))));
	connector.setHandler(new TimeClientHander());
	ConnectFuture connectFuture = connector.connect(new InetSocketAddress("127.0.0.1", PORT));
	// 等待建立连接
	connectFuture.awaitUninterruptibly();
	System.out.println("连接成功");
	IoSession session = connectFuture.getSession();
	Scanner sc = new Scanner(System.in);
	boolean quit = false;
	while (!quit) {
		String str = sc.next();
		if (str.equalsIgnoreCase("quit")) {
			quit = true;
		}
		session.write(str);
	}

	// 关闭
	if (session != null) {
		if (session.isConnected()) {
			session.getCloseFuture().awaitUninterruptibly();
		}
		connector.dispose(true);
	}

}
 
Example #9
Source File: CIMNioSocketAcceptor.java    From cim with Apache License 2.0 5 votes vote down vote up
private void bindAppPort() throws IOException {


		appAcceptor = new NioSocketAcceptor();
		((DefaultSocketSessionConfig) appAcceptor.getSessionConfig()).setKeepAlive(true);
		((DefaultSocketSessionConfig) appAcceptor.getSessionConfig()).setTcpNoDelay(true);

		KeepAliveFilter keepAliveFilter = new KeepAliveFilter(this, IdleStatus.BOTH_IDLE);
		keepAliveFilter.setRequestInterval(IDLE_HEART_REQUEST_TIME);
		keepAliveFilter.setRequestTimeout(HEART_RESPONSE_TIME_OUT);
		keepAliveFilter.setForwardEvent(true);

		appAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new AppMessageCodecFactory()));
		appAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
		appAcceptor.getFilterChain().addLast("heartbeat", keepAliveFilter);
		appAcceptor.getFilterChain().addLast("executor", new ExecutorFilter(createWorkerExecutor()));
		appAcceptor.setHandler(this);

		appAcceptor.bind(new InetSocketAddress(appPort));
		String logBanner = "\n\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"*                   App Socket Server started on port {}.                        *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
		LOGGER.info(logBanner, appPort);
	}
 
Example #10
Source File: HelloTcpServer.java    From mina-examples with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	IoAcceptor acceptor = new NioSocketAcceptor(); //TCP Acceptor
	acceptor.getFilterChain().addLast("logging", new LoggingFilter());
	acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
	acceptor.getFilterChain().addLast("mdc", new MdcInjectionFilter());
	acceptor.setHandler(new HelloServerHandler());
	acceptor.getSessionConfig().setReadBufferSize(2048);
	acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
	acceptor.bind(new InetSocketAddress(PORT));
}
 
Example #11
Source File: HelloUdpServer.java    From mina-examples with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	NioDatagramAcceptor acceptor = new NioDatagramAcceptor();//UDP Acceptor
	acceptor.getFilterChain().addLast("logging", new LoggingFilter());
	acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
	acceptor.getFilterChain().addLast("mdc", new MdcInjectionFilter());
	acceptor.setHandler(new HelloServerHandler());
	acceptor.getSessionConfig().setReadBufferSize(2048);
	acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
	DatagramSessionConfig dcfg = acceptor.getSessionConfig();
	dcfg.setReuseAddress(true);
	acceptor.bind(new InetSocketAddress(PORT));
}
 
Example #12
Source File: TftpServer.java    From tftp4j with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws IOException {
    acceptor = new NioDatagramAcceptor();
    acceptor.setDefaultLocalAddress(new InetSocketAddress(getPort()));
    acceptor.getFilterChain().addLast("logger-data", new LoggingFilter("tftp-server-data"));
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TftpProtocolCodecFactory()));
    acceptor.getFilterChain().addLast("logger-packet", new LoggingFilter("tftp-server-packet"));
    acceptor.setHandler(new TftpServerProtocolHandler(getDataProvider()));
    DatagramSessionConfig dcfg = acceptor.getSessionConfig();
    dcfg.setReuseAddress(true);
    // dcfg.setIdleTime(IdleStatus.BOTH_IDLE, 5);
    acceptor.bind();
}
 
Example #13
Source File: Tcp.java    From jlogstash-input-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void emit() {
	// TODO Auto-generated method stub
	try {
		// ssl 认证
		if (sslEnable) {
			SslFilter sslFilter = new SslFilter(getSslContext());
			acceptor.getFilterChain().addLast("sslFilter", sslFilter);
			logger.warn("ssl authenticate is open");
		}
		LoggingFilter loggingFilter = new LoggingFilter();
		acceptor.getFilterChain().addLast("logger", loggingFilter);
		TextLineCodecFactory textLineCodecFactory = new TextLineCodecFactory(
				Charset.forName(encodiing));
		textLineCodecFactory.setDecoderMaxLineLength(maxLineLength);
		textLineCodecFactory.setEncoderMaxLineLength(maxLineLength);
		acceptor.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(textLineCodecFactory));
		acceptor.setHandler(minaBizHandler);
		acceptor.getSessionConfig().setReadBufferSize(bufSize);
		acceptor.getSessionConfig().setWriteTimeout(10);
		// acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,
		// 10);//空闲状态
		acceptor.bind(new InetSocketAddress(InetAddress.getByName(host),
				port));
	} catch (Exception e) {
		// TODO Auto-generated catch block
		logger.error(e.getMessage());
		System.exit(1);
	}
}
 
Example #14
Source File: MinaTimeServer.java    From javabase with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	IoAcceptor acceptor = new NioSocketAcceptor();
	acceptor.getFilterChain().addLast("logger", new LoggingFilter());
	acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));// 指定编码过滤器
	acceptor.setHandler(new TimeServerHandler());// 指定业务逻辑处理器

	//读写 通道均在3 秒内无任何操作就进入空闲状态
	acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 3);

	acceptor.setDefaultLocalAddress(new InetSocketAddress(PORT));// 设置端口号
	acceptor.bind();// 启动监听
}
 
Example #15
Source File: MinaTimeClient.java    From javabase with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	// 创建客户端连接器.
	NioSocketConnector connector = new NioSocketConnector();
	connector.getFilterChain().addLast("logger", new LoggingFilter());
	connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); // 设置编码过滤器
	connector.setConnectTimeout(30);
	connector.setHandler(new TimeClientHandler());// 设置事件处理器
	ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1", 9123));// 建立连接
	cf.awaitUninterruptibly();// 等待连接创建完成
	cf.getSession().write("hello");// 发送消息
	cf.getSession().write("quit");// 发送消息
	cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开
	connector.dispose();
}
 
Example #16
Source File: StreamBaseDevice.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public synchronized void connect ()
{
    if ( isConnected () )
    {
        logger.info ( "Already connected" );
        return;
    }

    if ( this.connector == null )
    {
        this.connector = new NioSocketConnector ();
        this.connector.setHandler ( this );
        if ( Boolean.getBoolean ( "org.eclipse.scada.da.server.io.common.trace" ) )
        {
            this.connector.getFilterChain ().addLast ( "logger", new LoggingFilter () );
        }
        setupConnector ( this.connector );
    }

    final ConnectFuture cu = this.connector.connect ( this.address );
    cu.addListener ( new IoFutureListener<ConnectFuture> () {

        @Override
        public void operationComplete ( final ConnectFuture future )
        {
            try
            {
                future.getSession ();
            }
            catch ( final Throwable e )
            {
                StreamBaseDevice.this.fireConnectionFailed ( e );
            }
        }
    } );
}
 
Example #17
Source File: FilterChainBuilder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void buildFilterChain ( final IoFilterChain chain )
{
    if ( this.loggerName != null && Boolean.getBoolean ( "org.eclipse.scada.protocol.sfp.common.logger.raw" ) )
    {
        chain.addFirst ( "logger.raw", new LoggingFilter ( this.loggerName ) );
    }

    if ( !Boolean.getBoolean ( "org.eclipse.scada.protocol.sfp.common.disableStats" ) )
    {
        chain.addFirst ( StatisticsFilter.DEFAULT_NAME, new StatisticsFilter () );
    }

    if ( this.loggerName != null && Boolean.getBoolean ( "org.eclipse.scada.protocol.sfp.common.logger" ) )
    {
        chain.addFirst ( "logger", new LoggingFilter ( this.loggerName ) );
    }

    chain.addLast ( "closeidle", new IoFilterAdapter () {
        @Override
        public void sessionIdle ( final NextFilter nextFilter, final IoSession session, final IdleStatus status ) throws Exception
        {
            session.close ( true );
        }
    } );
    chain.addLast ( "codec", new ProtocolCodecFilter ( new ProtocolEncoderImpl (), new ProtocolDecoderImpl () ) );
}
 
Example #18
Source File: Application1.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object start ( final IApplicationContext context ) throws Exception
{
    final NioSocketConnector connector = new NioSocketConnector ();

    connector.setHandler ( new SingleSessionIoHandlerDelegate ( new SingleSessionIoHandlerFactory () {

        @Override
        public SingleSessionIoHandler getHandler ( final IoSession session ) throws Exception
        {
            return new DaveHandler ( session );
        }
    } ) );

    connector.getFilterChain ().addLast ( "logger", new LoggingFilter ( this.getClass ().getName () ) );
    connector.getFilterChain ().addLast ( "tpkt", new TPKTFilter ( 3 ) );
    connector.getFilterChain ().addLast ( "cotp", new COTPFilter ( 0, (byte)3 ) );
    connector.getFilterChain ().addLast ( "dave", new DaveFilter () );

    connector.connect ( new InetSocketAddress ( "192.168.1.83", 102 ) );

    while ( this.running )
    {
        Thread.sleep ( 1000 );
    }

    return null;
}
 
Example #19
Source File: MinaStartup.java    From seed with Apache License 2.0 5 votes vote down vote up
public final void bind() throws IOException {
    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    //这里并未配置backlog,那么它会采用操作系统默认的连接请求队列长度50
    //详见org.apache.mina.core.polling.AbstractPollingIoAcceptor类源码的96行
    //acceptor.setBacklog(0);
    acceptor.setReuseAddress(this.reuseAddress);
    acceptor.getSessionConfig().setWriteTimeout(this.writeTimeout);
    acceptor.getSessionConfig().setBothIdleTime(this.bothIdleTime);
    //这里有个鱼和熊掌不可兼得的情景
    //若将codec定义在executor的前面,则codec由NioProcessor-1线程处理,IoHandler由pool-1-thread-1线程处理
    //若将codec定义在executor的后面,则codec和IoHandler都由pool-1-thread-1线程处理
    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ServerProtocolCodecFactory()));
    acceptor.getFilterChain().addLast("executor", new ExecutorFilter());
    //注意:无论如何executor都要定义在NioSocketConnector.setHandler()的前面
    acceptor.setHandler(this.handler);
    if(null==this.socketAddresses || this.socketAddresses.size()<1){
        throw new RuntimeException("监听SocketAddress数不得小于1");
    }
    acceptor.bind(this.socketAddresses);
    if(acceptor.isActive()){
        System.out.println("写 超 时: " + this.writeTimeout + "ms");
        System.out.println("发呆配置: Both Idle " + this.bothIdleTime + "s");
        System.out.println("端口重用: " + this.reuseAddress);
        System.out.println("服务端初始化完成...");
        System.out.println("服务已启动...开始监听..." + acceptor.getLocalAddresses());
    }else{
        System.out.println("服务端初始化失败...");
    }
}
 
Example #20
Source File: TftpServerProtocolHandler.java    From tftp4j with Apache License 2.0 4 votes vote down vote up
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
    TftpPacket packet = (TftpPacket) message;

    SocketAddress address = session.getRemoteAddress();
    LOG.info("Address is " + address);

    switch (packet.getOpcode()) {
        case RRQ: {
            TftpRequestPacket request = (TftpRequestPacket) packet;
            TftpData source = provider.open(request.getFilename());
            if (source == null) {
                session.write(new TftpErrorPacket(address, TftpErrorCode.FILE_NOT_FOUND), address);
                session.close(false);
            } else {
                final NioDatagramConnector connector = new NioDatagramConnector();
                TftpTransfer transfer = new TftpReadTransfer(address, source, request.getBlockSize());
                TftpTransferProtocolHandler handler = new TftpTransferProtocolHandler(connector, transfer);
                connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TftpProtocolCodecFactory()));
                connector.getFilterChain().addLast("logger-packet", new LoggingFilter("tftp-transfer-packet"));
                connector.setHandler(handler);
                ConnectFuture future = connector.connect(address);
                future.addListener(handler);
            }
            break;
        }
        case WRQ: {
            session.write(new TftpErrorPacket(address, TftpErrorCode.PERMISSION_DENIED), address);
            session.close(false);
            break;
        }
        case ACK: {
            break;
        }
        case DATA: {
            LOG.warn("Unexpected TFTP " + packet.getOpcode() + " packet: " + packet);
            session.write(new TftpErrorPacket(address, TftpErrorCode.ILLEGAL_OPERATION), address);
            session.close(false);
            break;
        }
        case ERROR: {
            TftpErrorPacket error = (TftpErrorPacket) packet;
            LOG.error("Received TFTP error packet: " + error);
            session.close(true);
            break;
        }
    }
}
 
Example #21
Source File: CalculatorClient.java    From mina with Apache License 2.0 4 votes vote down vote up
@Override
    public void run() {
        IoConnector connector = new NioSocketConnector();
        connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);//设置连接超时时间(毫秒数)
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CommandCodecFactory("UTF-8")));

        KeepAliveMessageFactoryImpl kamfi = new KeepAliveMessageFactoryImpl();
        KeepAliveFilter kaf = new KeepAliveFilter(kamfi, IdleStatus.READER_IDLE, KeepAliveRequestTimeoutHandler.CLOSE);
        /** 是否回发 */
        kaf.setForwardEvent(true);
        connector.getFilterChain().addLast("heart", kaf);

        connector.setHandler(new CalculatorClientHander());
        ConnectFuture connectFuture = connector.connect(new InetSocketAddress(IP, PORT));
        //等待建立连接
        connectFuture.awaitUninterruptibly();

        if(!connectFuture.isConnected()){
            log.debug("连接失败");
            return ;
        }
        log.debug("连接成功");

        IoSession session = connectFuture.getSession();

//        try {
//            Cmd1003 cmd1003 = (Cmd1003) CommandFactory.createCommand(CidConst.C1003);
//            cmd1003.getReqMsg().setCpu(0.3f);
//            cmd1003.getReqMsg().setDisk(0.24f);
//            cmd1003.getReqMsg().setMemory(0.41f);
//            session.write(cmd1003);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


        //关闭
        if (session != null) {
            if (session.isConnected()) {
                session.getCloseFuture().awaitUninterruptibly();
            }
            connector.dispose(true);
        }
    }