我正在使用以下代码进行telnet操作。问题是,如果我不使用setSoTimeout(),它每次都成功连接到Telnet服务器;但是,如果使用它,成功连接的频率降低到50%。它的使用方式有什么不对吗?
我实际上需要socket来抛出超时异常,原因各种各样,所以我需要使用setSoTimeout。请建议如何以有效运作的方式使用它。
public class TelnetClientHandle {
private TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
public TelnetClientHandle(String server, String user, String password) {
try {
telnet.setDefaultTimeout(20000);
try {
telnet.connect(server, 23, sourceIP, 0);
} catch (Exception e) {
return_value = "Unable to establish Telnet Connection with Server";
return;
}
}
}
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
String read_value = readUntil("login", true);
System.out.println(read_value);
if (read_value.contains("login")) {
write(user);
read_value = readUntil("sword", false);
System.out.println(read_value);
write(password);
} else {
return_value = "Unable to establish Telnet Connection with Server";
return;
}
telnet.setSoTimeout(2000);
read_value = readUntil("ABCDEFGH", false);
System.out.println(read_value);
if ((read_value == null)
|| ((read_value != null && !(read_value.toLowerCase()
.contains("last login") || read_value
.toLowerCase().contains("microsoft"))))) {
return_value = "Login error: Incorrect credentials or Server denied connection";
return;
}
} catch (Exception e) {
return_value = "Exception occurred: " + e.getMessage();
}
}
public String readUntil(String pattern, boolean checkForAvailableStream) {
StringBuffer sb = null;
try {
char lastChar = pattern.charAt(pattern.length() - 1);
sb = new StringBuffer();
char ch = (char) in.read();
while (true) {
sb.append(ch);
if (ch == lastChar) {
if (sb.toString().endsWith(pattern)) {
return sb.toString();
}
}
if ((checkForAvailableStream) && (in.available() > 0)) {
ch = (char) in.read();
} else if (!checkForAvailableStream) {
ch = (char) in.read();
} else
break;
}
} catch (Exception e) {
}
return sb.toString();
}
public void write(String value) {
try {
out.write((value + "\r\n").getBytes("CP1252"));
out.flush();
} catch (Exception e) { return_value = "Exception occurred in sending command to Server: "
+ e.getMessage();
}
}
public void disconnect() {
try {
telnet.disconnect();
} catch (Exception e) {
"Exception occurred: " + e.getMessage());
}
}
}
}