Reputation: 151
I'm trying to create a simple library (hope to share it with the world) that will allow to send and receive commands to remote equipment via telnet.
I'm trying to keep the code as simple as possible and it's already working, but I can't seem to understand how the input stream is working;
I'm reading each line separately and normally input should stop at input "Username:" after which I should type in my username.
What actually happens is that after I detect that I've received this line and send a response it is already too late (new input has already been received). Any idea how a telnet session actually works and how the last command (after which the remote equipment waits) is received?
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){}
}
}
Upvotes: 1
Views: 604
Reputation: 25380
A telnet server and telnet client don't just send plain text back and forth. There is a telnet protocol, and both the client and server can send commands to each other. The telnet server that you are connecting to may be trying to negotiate some setting change with your program, and your program may be interpreting the byte stream as lines of text.
The standard Unix telnet client program will suppress using the telnet protocol when it's not talking to an actual telnet server. Instead, it will fall back to sending text line-by-line and printing anything received from the server. This allows the program to be used to communicate with SMTP servers, HTTP servers, and the like. The telnet server doesn't necessarily have this fallback behavior; it may always assume that the client implements the protocol.
Upvotes: 1