java telnet socket : BufferedReader / BufferedWrit

2019-04-29 23:02发布

My server opens a telnet port on 23999 and when I give telnet localhost 23999, it shows below :

< 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 )

Now Instead of open like this, I have to write java code which does this thing.

  1. connect to host 23999 port
  2. enter password
  3. enter commad

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

This is not working.Actually, I am bit confused what approach I should follow.Very much confused between reader/writer.

Please help.

1条回答
神经病院院长
2楼-- · 2019-04-29 23:16

Only need to get socket input stream and output stream once (do this outside the while loop). Try something like this:

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

For accessing Telnet protocol you might be better off using a library such as Apache Commons Net rather than do it yourself.

查看更多
登录 后发表回答