All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.hasor.tconsole.client.TelnetClient Maven / Gradle / Ivy

There is a newer version: 4.2.5
Show newest version
/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.hasor.tconsole.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import net.hasor.tconsole.CommandExecutor;
import net.hasor.utils.future.BasicFuture;

import java.io.BufferedReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
 * simple telnet client.
 */
public final class TelnetClient {
    public static String executeCommand(String host, int port, String command) throws Exception {
        StringWriter returnData = new StringWriter();
        doExecuteCommand(host, port, command, new HashMap<>(), returnData);
        return returnData.toString();
    }
    public static String executeCommand(String host, int port, String command, Map envMap) throws Exception {
        StringWriter returnData = new StringWriter();
        doExecuteCommand(host, port, command, envMap, returnData);
        return returnData.toString();
    }
    //
    private static void doExecuteCommand(String host, int port, final String command, Map envMap, StringWriter returnData) throws Exception {
        //
        StringWriter commands = new StringWriter();
        if (envMap != null) {
            for (String key : envMap.keySet()) {
                String val = envMap.get(key);
                commands.write("set " + key + " = " + val + " \n");
            }
        }
        commands.write("set " + CommandExecutor.AFTER_CLOSE_SESSION + " = true \n");
        commands.write(command + "\n");
        //
        EventLoopGroup group = new NioEventLoopGroup();
        final BasicFuture closeFuture = new BasicFuture<>();
        final AtomicBoolean atomicBoolean = new AtomicBoolean(true);
        try {
            Bootstrap b = new Bootstrap();
            b = b.group(group);
            b = b.channel(NioSocketChannel.class);
            b = b.handler(new ChannelInitializer() {
                public void initChannel(SocketChannel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new TelnetClientHandler(closeFuture, atomicBoolean, returnData));
                }
            });
            Channel ch = b.connect(host, port).sync().channel();
            ChannelFuture lastWriteFuture = null;
            BufferedReader commandReader = new BufferedReader(new StringReader(commands.toString()));
            for (; ; ) {
                if (atomicBoolean.get()) {
                    String line = commandReader.readLine();
                    if (line == null) {
                        break;
                    }
                    if (ch.isActive()) {
                        atomicBoolean.set(false);
                        lastWriteFuture = ch.writeAndFlush(line + "\r\n");
                    }
                } else {
                    Thread.sleep(500);//等待指令的响应
                }
            }
            if (lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        } finally {
            closeFuture.get();
            group.shutdownGracefully();
        }
    }
}