我正在尝试创建一个简单的库(希望与世界分享),它允许通过 telnet 向远程设备发送和接收命令。
我试图使代码尽可能简单并且它已经在工作,但我似乎无法理解输入流是如何工作的;
我正在分别阅读每一行,通常输入应该在输入“用户名:”处停止,然后我应该输入我的用户名。
实际发生的情况是,在我检测到我已收到此行并发送响应后,已经为时已晚(已经收到新的输入)。知道 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){}
}
}