我遇到了一个非常奇怪的问题,这两天一直让我感到沮丧。我尝试在这里寻找类似的问题,但没有找到解决方案。
我正在使用套接字从远程 telnet session 记录器读取 Java 中的文件。
我为输入和输出流定义了 BufferedWriter 和 Reader,并将每个 readLine 刷新到文件中。登录时,我获取某个字符串,使用 outputStream 插入密码,然后开始循环读取流内内容。这在 Windows 上运行得很好,没有任何问题。
现在,我尝试在 Mac OS X (Yosemite) 上运行相同的代码。我得到第一行(要求我插入密码),通过调试我注意到我也将密码写入 BufferedWriter。但是,由于某种奇怪的原因,在下一个 readLine 迭代中,代码没有获得日志输出,而是挂起,卡在下一个 readLine 实例上。如果它为空,则应该退出循环。我已经检查过在 Mac 上手动打开 telnet session (使用 secureCRT),并且使用密码可以正常工作。在插入错误的密码时,我还应该得到一行(“密码不正确”)。但是在下一个 readLine 上我什么也没得到,它只是卡住了。
这是我的代码,有人知道我在这里做错了什么吗?它在 MAC 上的工作方式应该有所不同吗?它真的可以拯救我在这里。谢谢!
这个片段是线程的一部分,但它与问题无关(或者我认为是这样)。实际文件本身是在线程外部创建的。
public void run(){
String line = "-1";
try {
socket = new Socket(JSONReader.getPropertyByName("files/properties.json", "LOGGER_DNS_NAME"), 5550);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
instream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((line = instream.readLine()) != null) {
// Insert Username and Password in the Telnet session
line = instream.readLine();
if(line.startsWith("Please")){
bw.write("password");
bw.newLine();
bw.flush();
}
if (line.startsWith("Press")) {
System.out.println("Reached log");
bw.write("d");
bw.newLine();
bw.flush();
}
if (Thread.interrupted()){
try {
instream.close();
bw.close();
socket.close();
return;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Could not close socket");
System.exit(-1);
}
}
}
// Write the output to the log file
logfile.println(line);
logfile.flush();
} catch (UnknownHostException e) {
System.out.println("Could not open Telnet session to the server");
System.exit(1);
} catch (IOException e) {
System.out.println("There was a problem with file creation, or I/O exception");
System.exit(1);
}
}
最佳答案
最后,在两种情况下嗅探服务器的 tcp session 后,我发现了我的问题。
问题在于 BufferedWriter 在使用写入方法、新行和刷新时会自动生成行结尾 (\n)。异常(exception)的是,在基于 Linux 的 Mac OS 上,行结尾应该是 (\r\n)。
因此,我没有使用“write”方法和“换行”,而是使用“append”插入\r\n 字符串(append ("password\r\n))。
关于java - BufferedWriter 在 OS X 上未刷新到套接字的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31158957/