Example usage for io.netty.channel.socket SocketChannel isActive

List of usage examples for io.netty.channel.socket SocketChannel isActive

Introduction

In this page you can find the example usage for io.netty.channel.socket SocketChannel isActive.

Prototype

boolean isActive();

Source Link

Document

Return true if the Channel is active and so connected.

Usage

From source file:net.hasor.rsf.console.launcher.TelnetClient.java

License:Apache License

public static void execCommand(String host, int port, final String command, Map<String, String> envMap)
        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");
        }/*from w w  w .  ja v  a  2  s.  c om*/
    }
    commands.write("set SESSION_AFTERCLOSE = true \n");
    commands.write(command + "\n");
    //
    EventLoopGroup group = new NioEventLoopGroup();
    final BasicFuture<Object> closeFuture = new BasicFuture<Object>();
    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<SocketChannel>() {
            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));
            }
        });
        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();
    }
}