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

标签 java sockets telnet

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

底线是我需要启动并运行一个快速但肮脏的 java telnet 应用程序,不一定是可扩展的,也不一定是漂亮的,所以我试图避免使用库、系统函数调用等。我一直在尝试和测试,到目前为止,当我尝试登录路由器时(当然是通过 telnet),我没有……什么都没有。

这是到目前为止我一直在使用的代码片段,请有人给我指出正确的方向,因为我不知道我还应该尝试什么,因为我确信它必须是真正的东西我想念的简单而愚蠢。提前致谢!

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看起来很容易使用。

该网站还说了以下内容:

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

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

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

关于使用套接字的java简单telnet客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6399557/

相关文章:

java - 使用 Kryo 序列化的 Netty 编码器和解码器

java - Java 文字真的是常量吗?

c# - 用于 Telnet 的 TcpClient Stream streamReader.ReadToEnd()

sockets - 通过套接字发送命令,但每次都等待响应 (Node.js)

java - 使用继承的 AssertJ usingComparatorForType 方法

java - 如何在邮件服务器上测试安全 SMTP 邮件服务

c# - SslStream .read() 一旦数据包返回第一个字节

ios - 带身份验证的 Swift Telnet 流

error-handling - 可以使用MozRepl从telnet正常退出吗?

Java实现htonl