2013-05-01 169 views
1

我正在嘗試創建一個簡單的庫(希望與全世界共享),它允許通過telnet發送和接收遠程設備的命令。Telnet基本IO操作

我試圖保持代碼儘可能簡單,它已經工作,但我似乎無法理解輸入流如何工作;

我正在單獨閱讀每一行,通常輸入應停止在輸入「用戶名:」之後,我應該鍵入我的用戶名。

實際發生的事情是,在檢測到我已收到此行併發送響應之後,它已經太晚了(已收到新輸入)。 是否知道telnet會話如何實際工作以及如何接收最後的命令(在遠程設備之後等待)?

import java.util.*; 
import java.io.*; 
import java.net.*; 


public class telnet { 



public static void main(String[] args){ 

    try{ 
     //socket and buffer allocation 
     Scanner scan = new Scanner (System.in); 
     Socket socket = null; 
     PrintWriter out;         
     BufferedReader in; 
     String input;   // temp input 
     String input1=""; 
     String buff = "";  // holds all the input 


     //socket and IO initialization 
     socket = new Socket("10.10.10.2", 23); 
     out = new PrintWriter(socket.getOutputStream(),true); 
     in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 


     int i=0; 
     int j=0; 
     while(true){ 
      input = in.readLine();      //printout given line 
      System.out.println("line "+i+":\n"+input); 


      if (input.contains("Username")){   //if reading 'username' send response 
       System.out.println("!got Username"); 
       out.println("user"); 
       continue; 
      } 

      if (input1.contentEquals(input)){   //if input is the same wait once then send ENTER 
       if (j==0){ 
        System.out.println("!read same line. wait for new"); 
        i++; j++; 
        continue; 
       } 
       else{ 
        System.out.println("!no new line. sending ENTER"); 
        out.println("\r"); 
        i++;j=0; 
       } 

      } else {j=0;} 



      input1="";     //copy input to temp string to check if same line or new 
      input1.concat(input); 
      i++; 
      if (i==20) break; 
     } 




     //CLOSE 
     out.close();          
     in.close(); 
     socket.close();         
    } catch(IOException e){} 
} 
} 

回答

1

遠程登錄服務器和遠程登錄客戶端不僅僅來回發送純文本。 There is a telnet protocol,並且客戶端和服務器都可以向對方發送命令。您正在連接的telnet服務器可能正試圖與您的程序協商一些設置更改,並且您的程序可能會將字節流解釋爲文本行。

標準的Unix遠程登錄客戶端程序將在不與實際的遠程登錄服務器通話時使用遠程登錄協議進行壓縮。相反,它將回退到逐行發送文本並打印從服務器收到的任何內容。這允許程序用於與SMTP服務器,HTTP服務器等進行通信。 Telnet服務器不一定具有此回退行爲;它可能總是假設客戶端實現協議。