我为向路由器发送命令编写了一种“期望”类型的实现。
我观察到的是,连接输入的处理速度要慢得多。
我的代码如下,
public static String expect(String expectString) {
try {
int c = 0;
while ((c = br.read()) != -1) {
expectBuffer.append((char) c);
System.out.print((char) c);
if (expectBuffer.toString().contains(expectString)) {
break;
}
}
String expBuff = expectBuffer.toString();
expectBuffer.setLength(0);
// System.out.println(expBuff);
return expBuff;
} catch (Exception e) {
return "";
}
}
public static void send(String cmd) {
pw.print(cmd + "\r");
pw.flush();
}
从 中main
,我将它们称为如下,
socket = new Socket();
socket.connect(new InetSocketAddress(server, 23), 10000);//Will wait for 10 seconds
socket.setKeepAlive(true);
socket.setSoTimeout(10000);
expectBuffer = new StringBuilder();
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(), true);
expect("Login");
send("dinesh");
expect("Password");
send("stack");
expect(server + "#");
send("some command here");
expect(server + "#");
处理输入并在控制台中打印需要花费很多时间。
任何人都可以提供有关改进我的代码的建议吗?
提前致谢。