common-net实现telnet客服端

TelnetClientClass.java
package com.abcom;

import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TelnetOption;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
import org.apache.log4j.Logger;

public class TelnetClientClass {
    Logger logger   = Logger.getLogger(TelnetClientClass.class);
    private TelnetClient tc = new TelnetClient();
    private TelnetClientEngine engine;
    private TelnetReceivedHandler handler;
    private OutputStream outstr_ = null;
    private boolean terminal     = false;
    
    private String serverName       = "";
    private String serverIPAdress   = "";
    private int    serverPort       = 23;
    
    private class TelnetClientEngine implements Runnable
    {
        private TelnetClientClass stc;
        private Thread engineThread;
        
        public TelnetClientEngine(TelnetClientClass stc)
        {
            this.stc     = stc;
        }
        
        public void begin()
        {
            engineThread = new Thread(this);
            engineThread.start();
        }
        
        public void irrupt() throws Exception
        {
            engineThread.interrupt();
            engineThread.join();
        }
        
        public boolean end()
        {
            try
            {
                stc.getTC().disconnect();
            }
            catch(Exception e)
            {
                logger.error("TelnetClientEngine:", e);
            }
            
            return false;
        }
        
        public void run()
        {
            outstr_           = stc.getTC().getOutputStream();
            InputStream instr = stc.getTC().getInputStream();
            try
            {
                byte[] buff = new byte[1024];
                int ret_read = 0;
                do
                {
                    ret_read = instr.read(buff);
                    if(ret_read>0)
                    {
                        handler.callback(buff, ret_read);
                    }
                }
                while(ret_read >= 0);
            }
            catch (Exception e)
            {
                logger.warn("Exception: ", e);
            }
            finally
            {
                if(terminal)
                    ;
                else
                {
                    this.begin();
                }
            }
        }
    }
    
    public TelnetClientClass(String name, String address, int port)
    {
        this.serverName         = name;
        this.serverIPAdress     = address;
        this.serverPort         = port;
    }
    
    public void setHandler(TelnetReceivedHandler handler)
    {
        this.handler    = handler;
    }
    
    public boolean start()
    {
        if(!setOption())
            return false;
        if(!connect())
            return false;
        
        engine   = new TelnetClientEngine(this);
        engine.begin();
        
        return true;
    }
    
    public void stop()
    {
        try
        {
            this.terminal   = true;
            this.removeOption();
            engine.end();
            
            return ;
        }
        catch(Exception e)
        {
            logger.error("Exception:", e);
        }
        
        logger.info("Shut down Telnet Client Thread failed, so force to kill.");
        
        try
        {
            engine.irrupt();
        }
        catch(Exception e)
        {
            logger.error("Exception:", e);
        }
    }
    
    private boolean connect()
    {
        logger.info("Connect to " + serverName + ":" + serverIPAdress + ", " + serverPort + ".");
        try
        {
            tc.connect(serverIPAdress, serverPort);
        }
        catch (Exception e)
        {
            logger.warn("Exception:", e);
            return false;
        }
        logger.info("Connected to " + serverName + " successful.");
        return true;
    }
    
    private boolean setOption()
    {
        TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("", false, false, true, false);
        EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
        SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
        
        try
        {
            tc.addOptionHandler(ttopt);
            tc.addOptionHandler(echoopt);
            tc.addOptionHandler(gaopt);
        }
        catch (InvalidTelnetOptionException e)
        {
            logger.warn("Exception: ", e);
            return false;
        }
        return true;
    }
    
    private void removeOption() throws Exception
    {
        tc.deleteOptionHandler(TelnetOption.TERMINAL_TYPE);
        tc.deleteOptionHandler(TelnetOption.ECHO);
        tc.deleteOptionHandler(TelnetOption.SUPPRESS_GO_AHEAD);
    }
    
    private TelnetClient getTC()
    {
        return tc;
    }
    
    public boolean send(byte[] byteArray)
    {
        try
        {
            outstr_.write(byteArray, 0, byteArray.length);
            outstr_.flush();
        }
        catch (Exception e)
        {
            logger.error("Exception:",e);
            return false;
        }
        return true;
    }
}



TelnetSendHandler.java
package com.abcom;

public class TelnetSendHandler {
    private String serverName       = "";
    private String serverIPAdress   = "";
    private int    serverPort       = 23;
    
    private TelnetClientClass telnetclient;
    
    public TelnetSendHandler(String serverName, String serverIPAdress, int serverPort)
    {
    	this.serverName		= serverName;
    	this.serverIPAdress	= serverIPAdress;
    	this.serverPort		= serverPort;
    }
    
    public void initiation()
    {
    	telnetclient	= new TelnetClientClass(this.serverName, this.serverIPAdress, this.serverPort);
    }
    
    public TelnetClientClass getS12TelnetClient()
    {
    	return this.telnetclient;
    }
    
    public boolean send(byte[] byteArray)
    {
    	return this.telnetclient.send(byteArray);
    }

}



TelnetReceivedHandler.java
package com.abcom;

public abstract class TelnetReceivedHandler {
    public abstract void callback(byte[] buff, int length);
}


测试类:Telnet.java
package com.abcom;

public class Telnet extends TelnetReceivedHandler {

	@Override
	public void callback(byte[] buff, int length) {
		// TODO Auto-generated method stub
		System.out.println(new String(buff, 0, length));

	}
	
	public static void main(String[] args)
	{
		try
		{
			TelnetSendHandler telnetSendHandler = new TelnetSendHandler("test", "192.168.8.110", 23);
			telnetSendHandler.initiation();
			telnetSendHandler.getS12TelnetClient().setHandler(new Telnet());
			if(telnetSendHandler.getS12TelnetClient().start())
			{
				telnetSendHandler.send("root\r\n".getBytes());
				Thread.sleep(1000);
				telnetSendHandler.send("123456\r\n".getBytes());
				Thread.sleep(1000);
				telnetSendHandler.send("ls -l\r\n".getBytes());
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

}

你可能感兴趣的:(java,apache,thread,log4j,.net)