BufferedWriter 未刷新到 OS X 上套接字的外流

BufferedWriter not flushing to a socket's outstream on OS X

我遇到了一个非常奇怪的问题,过去两天让我很沮丧。我试过在这里寻找类似的问题,但没有找到解决方案。

我正在使用套接字从远程 telnet 会话记录器读取文件,在 Java.
我已经为输入和输出流定义了一个 BufferedWriter 和 Reader,并将每个 readLine 刷新到一个文件中。在登录时,我得到一个特定的字符串,使用 outputStream 插入密码,然后开始循环读取 instream。这在 Windows 上完美运行,没有任何问题。

现在,我在 Mac OS X (Yosemite) 上尝试了 运行 相同的代码。我得到第一行(要求我插入密码),通过调试我注意到我也在将密码写入 BufferedWriter。但是,由于某些奇怪的原因,在下一次 readLine 迭代中,代码没有获得日志输出,而是挂起,卡在下一个 readLine 实例上。如果它为空,则应该退出循环。我检查了在 mac 上手动(使用 secureCRT)打开 telnet 会话,并且它可以使用密码 O.K。在输入错误的密码时,我也应该得到一行(“密码不正确”)。但是在下一个 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 会话后,我发现了我的问题。

问题是 BufferedWriter 在使用 write 方法、换行和刷新时自动生成行结束符 (\n)。除了基于 linux 的 Mac OS,行结尾应该是 (\r\n)。

所以,我没有使用 "write" 方法和 "new line",而是使用 "append" 插入了 \r\n 字符串(附加(“密码\r\n)).