Java TelnetClient 在“按任意键继续”时挂起
-
16-09-2019 - |
题
我有一个在 Linux 上运行的 Java 程序,并使用 telnet 到远程服务器 org.apache.commons.net.telnet.TelnetClient
并执行一些命令。问题是,当它到达要求用户“按任意键继续…”的输出显示时,它会间歇性挂起。该程序每运行 10 次就有 1 次挂起,在我运行它的 7 台服务器中只有 3 台服务器出现问题。另外,当我在 Windows 机器上运行相同的程序时,它始终有效。
我想知道其他人是否也遇到过这样的问题?
在测试服务器上,我每次都可以让它挂起进行测试。我尝试发送其他不会导致它挂起的命令,但没有成功。我已经尝试了所有的回车、换行、添加字符和换行。似乎没有什么能让客户继续。
忘了说我首先想到的就是刷新缓冲区。我将刷新命令放在我认为可能有帮助的任何地方。
我还要提到,当我运行它并观察写入行的输出时,它确实找到“按任意键”并继续运行,但挂起终端不继续。
我拨打电话的代码:
readUntil("X) Exit (no report)");
write("C", false);
out.flush();
readUntil("continue....");
// write this for all servers.
write("", true);
out.flush();
readUntil("X) Exit");
write("X", false);
/*
* This method is used to read the command line until the pattern that was
* passed in is found.
*/
public String readUntil(String pattern) throws Exception {
try {
String tempString;
char lastChar = pattern.charAt(pattern.length() - 1);
StringBuffer sb = new StringBuffer();
//boolean found = false;
char ch = (char) in.read();
while (true)
{
// NOTE: Turn line below on to watch the program perform the telnet
System.out.print(ch);
sb.append(ch);
tempString = sb.toString();
if (ch == lastChar) {
if (tempString.endsWith(pattern))
{
// log to file
logFileWriter.write(tempString);
logFileWriter.flush();
return tempString;
}
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/*
* writes the String passed in to the command line.
* boolean userWriteln: true - use the return key after the command, false - just type the
* command with NO enter key
*/
public void write(String value, boolean useWriteln)
{
System.out.println("WRITTING '" + value + "'");
try {
if (useWriteln)
{
out.println(value);
}
else
{
out.print(value);
}
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}
堆栈跟踪:java.net.SocketTimeoutException:在Java.socketInputStream.socketRead0(本机方法)上阅读时,请访问java.net.socketinputstream.read(socketInputStream.java:129),java.io.bufferedinputstream.fill(bufferedInputStream.java:218) BufferedInputStream.read(BufferedInputStream.java:237) at java.io.FilterInputStream.read(FilterInputStream.java:66) at java.io.PushbackInputStream.read(PushbackInputStream.java:122) at org.apache.commons.net.io 。 io.BufferedInputStream.read(BufferedInputStream.java:237) at org.apache.commons.net.telnet.TelnetInputStream.__read(TelnetInputStream.java:122) at org.apache.commons.net.telnet.TelnetInputStream.run(TelnetInputStream. Java:564)at Java.lang.thread.run(thread.java:619)
它挂在哪里:英语 1 6000 4462 26 % 13826 11056 20 %
Calls answered since Thu Jun 4, 2009 3:11 am: 41245
按任意键继续....
解决方案
可能有以下几个原因:
您没有刷新输出(远程命令的输入),因此永远不会发送“任意键”。
该程序尝试向您发送一些数据,但您从未读取您的输入(远程命令的输出)。请注意,您必须在第二个线程中执行此操作,因为 I/O 通常“同时”发生,如果您没有足够及时地处理另一侧,一侧将会阻塞。
也许您遇到问题是因为应用程序将终端转变为“RAW 模式”。但是刷新你的输出应该可以解决这个问题:/