我需要一些方向。不知道我是否在正確的道路上,但我認爲如此。我正在嘗試創建一個連接到客戶端機器的telnet java程序,執行單個命令然後斷開連接。當我連接到Linux機器或我的路由器時,我能夠使程序工作並將InputStream讀出到文本字段(用於測試目的)。但是,當我連接到Windows機器或其他客戶端計算機時,它不起作用。它讀出一些隨機字符,然後鎖定。的Telnet Java Socket技術測試
以下是我的代碼。我已經看到了其他代碼的例子以及來自Apache的API。我真的很想看看我能否只用Java套接字來工作。
public class TestSockets extends JFrame implements ActionListener {
/**
* @param args
*/
private String USER = "User";
private String PASS = "Password01";
private final static String CMD = "exit\r\n";
private static Socket telnet = null;
private PrintWriter writer = null;
private static InputStream reader = null;
private String host = "192.168.1.1";
private int port = 23;
TextArea javatext;
public static void main(String[] args) {
// TODO Auto-generated method stub
new TestSockets().setVisible(true);
}
private TestSockets() {
super("Testing Buttons");
//Set JFrame size
setSize(500, 600);
//Gives JFrame a location
setLocation(100, 100);
//set layout
setLayout(new FlowLayout());
javatext = new TextArea(25, 65);
add(javatext);
//Ask for window decorations provided by the look and feel.
JFrame.setDefaultLookAndFeelDecorated(true);
JButton button3 = new JButton("Run Program");
button3.addActionListener(this);
add(button3);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
try {
telnet = new Socket(host, port);
telnet.setKeepAlive(true);
//reader = telnet.getInputStream();
writer = new PrintWriter(telnet.getOutputStream());
reader = telnet.getInputStream();
//out = telnet.getOutputStream();
//Process p = Runtime.getRuntime().exec("telnet " + server.toString(), null, null);
//DataOutputStream os = new DataOutputStream(p.getOutputStream());
//DataInputStream in = new DataInputStream(p.getInputStream());
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[4096]; // Read 4K characters at a time
int len; // How many chars read each time
while ((len = reader.read(buffer)) != -1) {
String readchar = new String(buffer, 0, len);
sb.append(readchar + "\n");
System.out.println(readchar);
javatext.append(readchar);
if (readchar.endsWith("login: ")) {
writer.print(USER + "\r\n");
writer.flush();
}
if (readchar.endsWith("Password: ")) {
writer.print(PASS + "\r\n");
writer.flush();
}
if (readchar.endsWith("password: ")) {
writer.print(PASS + "\r\n");
writer.flush();
}
if (readchar.endsWith("# ")) {
writer.print(CMD);
writer.flush();
}
if (readchar.endsWith("# ")) {
writer.print(CMD);
writer.flush();
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
你怎麼知道什麼你得到居然是壞的數據?您可能會獲得某種認證數據。你能向我們提供輸出嗎?另外,你有什麼嘗試?從我讀到的 – 2012-03-13 23:49:43
,你是對的。這只是驗證數據。我的問題是,當我嘗試連接到Windows盒子時,它並沒有進一步發展。該程序適用於Linux和我的路由器。 – itgeek25 2012-03-14 14:23:54