gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:00:17 25 4
gpt4 key购买 nike

我已经阅读了很多关于该主题的内容,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com