Telnet Java套接字测试 [英] Telnet Java Socket Test

查看:148
本文介绍了Telnet Java套接字测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些方向。不知道我是否在正确的道路上,但我想是这样。我试图创建一个telnet java程序,将连接到客户端机器,执行单个命令,然后断开连接。我可以得到程序工作和读出InputStream到一个文本字段(用于测试目的)当我连接到一个linux机器或我的路由器。但是当我连接到Windows机器或其他客户端计算机,它不工作。它读出一些随机字符,然后锁定。

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.

下面是我的代码。我看到了其他代码的示例,以及来自Apache的API。我真的很想看看是否可以让这个只使用Java套接字。

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();
}
}

    }


推荐答案

感谢大家的帮助。我真的试图让这个工作在Android,但只是在直接的Java应用程序做一个草稿。我得到了粗略的想法,它的工作原理。它只是重复我的StringBuilder中的所有字符,如果我读取输出。不是一个大问题,我不是试图显示输出真的反正。这是我完成了。希望这可以帮助任何人,如果需要。

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();
    }
    }
    }

这篇关于Telnet Java套接字测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆