我在 telnet 会话中的 InputStream 遇到了一些问题。我已经建立了连接,我可以通过 telnet 成功发送命令,并且使用 System.out.println,我可以看到我收到了正确的响应。
我需要将会话的响应作为字符串返回,因为我需要对其执行正则表达式来验证测试的值。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.SocketException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.telnet.TelnetClient;
public class TelnetService {
private final String server;
private final int port;
private TelnetClient telnet = new TelnetClient();
private InputStream dataIn;
private PrintStream dataOut;
private String prompt = "~$";
public TelnetService(String server, int port) {
this.server = server.replace("http://", "");
this.port = port;
}
private void startTelnetSession() throws SocketException, IOException {
telnet.connect(server, port);
dataIn = telnet.getInputStream();
dataOut = new PrintStream(telnet.getOutputStream());
}
public String getTelnetSessionAsString() {
try {
startTelnetSession();
loginUser();
readUntil(prompt);
write("this_command");
readUntil(prompt);
StringWriter writer = new StringWriter();
IOUtils.copy(dataIn, writer, "UTF-8");
dataOut.flush();
dataIn.close();
dataOut.close();
String received = writer.toString();
telnet.disconnect();
return received;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void loginUser() {
readUntil("login:");
write("foo");
readUntil("Password:");
write("bar");
}
private void write(String value) {
try {
dataOut.println(value);
dataOut.flush();
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
private String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length() - 1);
StringBuffer buffer = new StringBuffer();
char ch = (char) dataIn.read();
while (true) {
System.out.print(ch);
buffer.append(ch);
if (ch == lastChar) {
if (buffer.toString().endsWith(pattern)) {
return buffer.toString();
}
}
ch = (char) dataIn.read();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
事实上,每当调用这个类的测试运行时,它似乎在
IOUtils.copy(dataIn, writer, "UTF-8");
我敢肯定,我缺少一些非常简单的东西。有没有人可以提供帮助?将不胜感激!