Telnet Java 套接字测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9693913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:15:38  来源:igfitidea点击:

Telnet Java Socket Test

javasocketsconnectiontelnet

提问by itgeek25

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.

我需要一些指导。不确定我是否走在正确的道路上,但我认为是这样。我正在尝试创建一个 telnet java 程序,该程序将连接到客户端计算机,执行单个命令然后断开连接。当我连接到 linux 机器或我的路由器时,我能够让程序工作并将 InputStream 读出到文本字段(用于测试目的)。但是当我连接到 Windows 机器或其他客户端计算机时,它不起作用。它读出一些随机字符,然后锁定。

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.

下面是我的代码。例如,我已经看到了其他代码的示例以及来自 Apache 的 API。我真的很想看看我是否可以让它只与 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();
}
}

    }

采纳答案by itgeek25

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.

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

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

回答by user207421

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

如果您看到的“随机字符”以 0xFF 字节开头,则它们是 Telnet 协议命令。

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

但是你还有另一个问题。不要在事件线程中执行长时间运行或阻塞的操作。使用单独的线程。

回答by Tim

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

Telnet 不仅仅是一个原始套接字,还有需要解释的发送(在每个方向)的控制代码。

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.

与其自己尝试这样做,不如使用现有的 Java Telnet 客户端库,例如Apache Commons Net 中的库