使用套接字的java简单telnet客户端 [英] java simple telnet client using sockets

查看:369
本文介绍了使用套接字的java简单telnet客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多关于这个主题的内容,telnet是一个协议,不是简单的套接字连接,等待换行符,使用外部库等等......

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

最重要的是,我需要一个快速而又脏的java telnet应用程序启动并运行,不一定可扩展,也不一定非常漂亮,所以我试图避免使用库,系统函数调用等。我一直在尝试和测试,到目前为止,当试图登录路由器(当然通过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. I have been trying and testing and so far, when trying to log into a router (through telnet of course) I have got... nothing.

这是一个剪断到目前为止,我一直在使用的代码,请有人指出我正确的方向,因为我不知道还应该尝试什么,因为我确定它必须是非常简单和愚蠢的东西,我是失踪。提前致谢!

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


推荐答案

如果没有测试,很难知道你的例子有什么问题针对您的特定路由器。使用库可能是个好主意,例如 http://sadun-util.sourceforge.net/telnet_library.html 看起来很容易使用。

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.

此网站还说明如下:


为了继续进行对话,只需在套接字的输出流上发送命令(并使用telnet换行序列\\\\ n)发出命令:

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



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




如果会话在登录后似乎挂起,请避免包装StreamWriter进入PrintWriter,而不是在结尾处运行显式flush():

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:



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

这可能实际上是您的代码的问题。

This might actually be the problem with your code.

这篇关于使用套接字的java简单telnet客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆