5

我的服务器在 23999 上打开了一个 telnet 端口,当我给出时telnet localhost 23999,它显示如下:

< BP-SAS ==> bplin19 !>telnet 0 23999
Trying 0.0.0.0...
Connected to 0.
Escape character is '^]'.
Please enter password to authenticate:
(here i give password for example abc123)   
Enter 'help' at any point to get a listing of all registered commands...
BAS> log set-info 1 ( commad i have entered and it does somthing )

现在,我必须编写执行此操作的 java 代码,而不是像这样打开。

  1. 连接主机 23999 端口
  2. 输入密码
  3. 输入逗号

Socket soc=new Socket("192.168.9.7",23999);
  while(true){
  //create buffered writer
  BufferedReader bwin = new BufferedReader(new InputStreamReader(soc.getInputStream()));
  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
  BufferedWriter bw1 = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
  String readFir = bwin.readLine();
  System.out.println(readFir);
        if(readFir.startsWith("Please")){
            System.out.println("Password Entered");
            bw.write("abc123");
            bw.flush();
            bw.close();  //close buffered Reader 
        }

        readFir = bwin.readLine();
        if(readFir.startsWith("Enter")){
            System.out.println("Enter command");
            bw1.write("log set-info 1");
            bw1.flush();
            bw1.close();  //close buffered Reader 
        }
        //readFir = bwin.readLine();
    }

这不起作用。实际上,我有点困惑我应该遵循什么方法。读者/作者之间非常困惑。

请帮忙。

4

1 回答 1

3

只需要获取一次套接字输入流和输出流(在 while 循环之外执行此操作)。尝试这样的事情:

Socket soc = new Socket("192.168.9.7",23999);
//create buffered writer
BufferedReader bwin = new BufferedReader(new InputStreamReader(soc.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
while (true) {
        String readFir = bwin.readLine();
        if (readFir == nul) break;
        System.out.println(readFir);
        if(readFir.startsWith("Please")){
            System.out.println("Password Entered");
            bw.write("abc123");
            bw.newLine();
            // instead might have to explicitly write "\r\n"
            // depending platform you're connecting from.
            bw.flush();
        }
        else if(readFir.startsWith("Enter")){
            System.out.println("Enter command");
            bw.write("log set-info 1");
            bw.newLine();
            bw.flush();
            bw.close();  //close buffered Writer
            break;
        } else System.out.println("Skip: " + readFir);
  }

要访问 Telnet 协议,最好使用Apache Commons Net之类的库,而不是自己动手。

于 2012-12-15T18:07:55.713 回答