简体   繁体   English

使用套接字的java简单telnet客户端

[英]java simple telnet client using sockets

I have read plenty of things on the topic, how telnet is a protocol, not a simple socket connection, waiting for newline characters, use of external libraries and whatnot... 我已经阅读了很多关于这个主题的内容,telnet是一个协议,不是简单的套接字连接,等待换行符,使用外部库等等......

The bottom line is that I need a quick and dirty java telnet application up and running, not necessarily scalable and not necessarily pretty, so I'm trying to avoid the use of libraries, system function calls and the like. 最重要的是,我需要一个快速而脏的java telnet应用程序启动和运行,不一定可扩展,不一定漂亮,所以我试图避免使用库,系统函数调用等。 I have been trying and testing and so far, when trying to log into a router (through telnet of course) I have got... nothing. 我一直在尝试和测试,到目前为止,当我尝试登录路由器(当然通过telnet)时,我得到了......没有。

Here is a snipped of the code that I have been using so far, please someone point me at the right direction because I don't know what else I should try, because I'm certain that it has to be something really simple and silly that I'm missing. 这是我到目前为止使用的代码的剪辑,请有人指出我正确的方向,因为我不知道还应该尝试什么,因为我确信它必须是非常简单和愚蠢的东西我失踪了。 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();

It's hard to know what's wrong with your example without testing against your particular router. 如果没有针对您的特定路由器进行测试,很难知道您的示例有什么问题。 It might be a good idea to use a library, for instance http://sadun-util.sourceforge.net/telnet_library.html looks like an easy one to use. 使用库可能是个好主意,例如http://sadun-util.sourceforge.net/telnet_library.html看起来很容易使用。

Also this site says the following: 此网站还说如下:

In order to carry on the conversation, a command is issued by simply sending it on the socket's outputstream (and using the telnet newline sequence \\r\\n): 为了进行对话,只需在套接字的输出流上发送一个命令(并使用telnet换行序列\\ r \\ n):

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

If the session appears to hang after login, avoid to wrap the StreamWriter into a PrintWriter and instead run an explicit flush() at the end: 如果会话在登录后似乎挂起,请避免将StreamWriter包装到PrintWriter中,而是在结尾处运行显式flush():

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

This might actually be the problem with your code. 这可能实际上是您的代码的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM