Java simple telnet client using sockets

I read a lot of things on this topic, like telnet is a protocol, not a simple connection of sockets, waiting for newlines, using external libraries, and more ...

The bottom line is that I need a fast and dirty telnet java application, not necessarily scalable and not necessarily beautiful, so I try to avoid the use of libraries, calls to system functions, etc. I try and test, and so far, when I try to enter the router (via telnet, of course), I have ... nothing.

Here is the code snippet that I have used so far, please call me in the right direction, because I don’t know what else I should try, because I’m sure that it should be something really simple and stupid that I lacks. Thanks in advance!

Socket socket = new Socket("192.168.1.1", 23); socket.setKeepAlive(true); BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter w = new PrintWriter(socket.getOutputStream(),true); int c=0; while ((c = r.read()) != -1) System.out.print((char)c); w.print("1234\r\n"); // also tried simply \n or \r //w.flush(); //Thread.sleep(1000); while ((c = r.read()) != -1) System.out.print((char)c); w.print("1234\r\n"); //Thread.sleep(1000); while ((c = r.read()) != -1) System.out.print((char)c); socket.close(); 
+6
source share
1 answer

It is difficult to understand what is wrong with your example, without testing on your specific router. It would be nice to use a library, for example http://sadun-util.sourceforge.net/telnet_library.html looks like easy to use.

This site also says the following:

To continue the conversation, the command is issued simply by sending it to the output stream of the socket (and using the sequence of the new line telnet \ r \ n):

  String command="print hello"; PrintWriter pw = new PrintWriter( new OutputStreamWriter(s.getOutputStream()), true); pw.print(command+"\r\n"); 

If the session freezes after logging in, avoid porting StreamWriter to PrintWriter and instead run the explicit flush () stream at the end:

  Writer w = new OutputStreamWriter(s.getOutputStream()); w.print(command+"\r\n"); w.flush(); 

This may be a problem with your code.

+10
source

Source: https://habr.com/ru/post/890838/


All Articles