Telnet Java Socket Test

14,797

Solution 1

Thanks for everyones help. I was really trying to get this to work in Android but just was making a rough draft in straight Java app. I got the rough idea and it works. It just repeats all the characters in my StringBuilder over and over if I read the output. Not a big concern, I am not trying to display the output really anyway. Here is what I finished with. Hope this helps anyone else if needed.

public class AndroidSocket extends Activity implements OnClickListener {

TextView text;
EditText edit1, edit2, edit3, edit4;
private String USER = null;
private String PASS = null;
Editable server, username, password, command;
private String CMD = null;
private PrintStream writer = null;
private static BufferedReader reader = null;
private String host = null;
private int port = 23;
private TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
StringBuffer sb;
Handler mHandler = new Handler();
int len; 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    text = (TextView)findViewById(R.id.text);
    edit1 = (EditText)findViewById(R.id.edit1);
    edit2 = (EditText)findViewById(R.id.edit2);
    edit3 = (EditText)findViewById(R.id.edit3);
    edit4 = (EditText)findViewById(R.id.edit4);

    server = edit1.getEditableText();
    username = edit2.getEditableText();
    password = edit3.getEditableText();
    command = edit4.getEditableText();

    Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(this);
    text.setText("Android Socket" + "\n");
    }

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    text.setText("Android Socket" + "\n");
    try {
        telnet.connect(server.toString(), 23);
        in = telnet.getInputStream();
        out = new PrintStream(telnet.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(telnet.getInputStream()));
        writer = new PrintStream(telnet.getOutputStream());
    telnet.setKeepAlive(true);
    Thread mThread = new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
             try {
                 sb = new StringBuffer();
                 //char[] buffer = new char[1024];
                    while (true)
                    { 
                            len = in.read();
                            String s = Character.toString((char)len);
                            sb.append( s );
                            AndroidSocket.this.mHandler.post(new Runnable(){

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    AndroidSocket.this.text.getText();
                                    AndroidSocket.this.text.append( sb.toString() );
                                }

                            });
                            System.out.println( sb );
                            mylogin();
                            mypass();
                            mycommand();
                        }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }

    });
    mThread.start();
    }
    catch (Exception e) {
    e.printStackTrace();
    }
}

     private void mycommand() throws IOException {
            // TODO Auto-generated method stub
if (sb.toString().endsWith("> ")) {
    out.println(command.toString() + "\r\n");
    out.flush();
    out.println("exit\r\n");
    out.flush();
    try {
        TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    disconnect();
} else
if (sb.toString().endsWith("# ")) {
    out.println(command.toString() + "\r\n");
    out.flush();
    out.println("exit\r\n");
    out.flush();
    try {
        TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    disconnect();
}
}

    private void mypass() {
    // TODO Auto-generated method stub
if (sb.toString().endsWith("Password: ")) {
    out.println(password.toString() + "\r\n");
    out.flush();
} else
if (sb.toString().endsWith("password: ")) {
    out.println(password.toString() + "\r\n");
    out.flush();
}
}

    private void mylogin() {
    // TODO Auto-generated method stub
if (sb.toString().endsWith("login: ")) {
    out.println(username.toString() + "\r");
    out.flush();
}
}

      public void disconnect() {
     try {
in.close();
out.close();
telnet.disconnect();

    }
    catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

Solution 2

Telnet isn't simply a raw socket, there are control codes that get sent (in each direction) that you need to interpret.

Rather than trying to do that yourself you'd be better off using an existing Java Telnet client library like the one in Apache Commons Net.

Solution 3

If the 'random characers' that you are seeing start with a 0xFF byte, they are Telnet protocol commands.

But you have another problem. Don't execute long-running or blocking operations in the event thread. Use a separate thread.

Share:
14,797
itgeek25
Author by

itgeek25

Updated on June 04, 2022

Comments

  • itgeek25
    itgeek25 almost 2 years

    I am in need of some direction. Not sure if I am on the right path but I think so. I am trying to create a telnet java program that will connect to a client machine, execute a single command then disconnect. I am able to get the program to work and readout the InputStream to a Text field ( for testing purposes) when I connect to a linux machine or my router. But when I connect to a Windows machine or other client computer, it doens't work. It reads out some random characters, then locks up.

    Below is my code. I have seen examples of other code out there as well as API's from Apache for example. I would really like to see if I can get this to work with just Java Sockets.

        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();
    }
    }
    
        }
    
  • itgeek25
    itgeek25 about 12 years
    I did try to create a new thread and run the write and reading code in seperate processes. Still the same issue. This is what boggles my mind. I don;t get any errors or problems, it just hangs when trying to connect to windows. Telnet works on the windows machine I am trying it on.
  • itgeek25
    itgeek25 about 12 years
    I have tried to use the Apache code on the windows box as well. Same issue, works with linux but not my windows machine. I have used someone elses application written in Java, this works great. I compared my code to theirs, which is slightly different but reads the input and output the same. Theirs works but mine doesn't. This is why I am pulling out the rest of my hair.
  • user207421
    user207421 about 12 years
    @itgeek25 your code assumes that each read is a whole line. Use readLine() and be sure.
  • Andrew Kozak
    Andrew Kozak about 12 years
    Congrats on the fix. When you are able, please mark your answer as 'accepted' to help others find your solution. Cheers~
  • user207421
    user207421 over 11 years
    @itgeek25 Please also note that although using a separate thread is definitely required, it won't solve the 'random' character problem.
  • Thufir
    Thufir over 10 years
    "The TelnetClient class used by itself is mostly intended for automating access to telnet resources rather than interactive use." svn.apache.org/repos/asf/commons/proper/net/tags/NET_1_0_0/s‌​rc/… not a useful library, IMHO