利用commons-net写的发送telnet命令的类

package test; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import org.apache.commons.net.telnet.TelnetClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TelnetBrowser { private static final Logger logger = LoggerFactory .getLogger(TelnetBrowser.class); private TelnetClient client; private String host; private int port; private PrintStream out; private BufferedReader in; public TelnetBrowser(String host, int port) { client = new TelnetClient(); this.host = host; this.port = port; } public void connect() throws TelnetException { try { client.connect(host, port); } catch (Exception e) { throw new TelnetException(e); } } public void disconnect() throws TelnetException { try { if (out != null) { out.close(); } if (in != null) { in.close(); } client.disconnect(); } catch (IOException e) { throw new TelnetException(e); } } public void sendCommand(String cmd) throws TelnetException { if (!client.isConnected()) { throw new IllegalStateException(); } if (out == null) { out = new PrintStream(client.getOutputStream()); } if (in == null) { InputStreamReader isr = new InputStreamReader(client.getInputStream()); in = new BufferedReader(isr); } try { out.print(cmd); out.flush(); String str = null; while ((str = in.readLine()) != null) { System.out.println(str); } } catch (IOException e) { throw new TelnetException(e); } } }

package test; @SuppressWarnings("serial") public class TelnetException extends Exception { public TelnetException() { super(); } public TelnetException(String error) { super(error); } public TelnetException(Throwable t) { super(t); } public TelnetException(String error, Throwable t) { super(error, t); } }

 

注意: while ((str = in.readLine()) != null) 处会发生阻塞,即当输出读取完毕时,在代码在此处会进行等待,直到有新的输出。

你可能感兴趣的:(exception,String,cmd,null,Class)