Java BufferedReader在Windows而非Mac上运行 [英] java BufferedReader works on windows and not mac

查看:76
本文介绍了Java BufferedReader在Windows而非Mac上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用BufferedReader或Scanner从服务器读取输出,但输出卡在read()或readLine()对象上.它永远不会从那一行返回.但是,它可以完美地在Windows上运行. 读取输出的代码如下所示:

I am trying to read an output from a server using BufferedReader or Scanner but it gets stuck on read() or readLine() objects. It never returns from that line. However, it is working on Windows perfectly. The code to read the output is seen below:

while ((serverResponce = this.in.readLine()) != null) {
            if (serverResponce.compareTo(message) == 0) {
                break;
            }
        }

或使用Scanner类:

or using Scanner class:

Scanner scanner = new Scanner(socket.getInputStream());
    while (scanner.hasNextLine())
    {
        serverResponce = scanner.nextLine();

        if (serverResponce.compareTo(message) == 0) {
              break;
         }
    }

我还尝试了BufferedReader中的ready()或扫描仪中的hasNextLine(),但没有任何用处.

I also tried ready() in BufferedReader or hasNextLine() in Scanner but without any use.

我对服务器的输出没有任何控制,所以我不知道它们使用哪种格式.它可以在Mac上使用telnet进行工作,但不能在Java应用程序内部使用.什么样的原因使它可以在Windows上运行,但被卡在Mac OS X上?

I don't have any control on the server's output so I don't know what kind of format they are using. It is working using telnet on Mac but not inside the java application. What kind of cause that makes it work on Windows but gets stuck on Mac OS X?

推荐答案

您不知道服务器正在发送什么,但是您正在使用试图逐行读取的字符串读取器.注意,线"在不同系统上的定义不同.在Windows中,行以"\ r \ n"终止,而在MacOS上,行以"\ r"或"\ n"终止,具体取决于版本.尝试逐字节读取,然后首先识别数据包终止符.

You don't know what the server is sending and yet you are using a string reader that tries to read line by line. Note that a "line" is defined differently on different systems. In Windows, a line is terminated by "\r\n", and on MacOS it is terminated by either "\r" or "\n", depending on the version. Try reading byte by byte, and identify the packet terminator first.

此外,如

Also, as explained here, just relying on ready() is not enough. It will return true if data is available (but that data might not be terminated by above mentioned line terminator, so readLine() would still block). If ready() returns false, it does not mean that the server is done sending data.

如果这仍然不能解决问题,则外部网络工具(例如 Wireshark )对于调试网络非常有用代码.如果您确实认为存在错误,请确保您具有独立于系统的代码,并且可以通过侦听自己的最小服务器来重现该问题.

If that still does not help you, external network tools, such as Wireshark are invaluable for debugging network code. If you really think that there is a bug, make sure you have system-independent code, and you can re-produce the problem by listening on your own minimal server.

这篇关于Java BufferedReader在Windows而非Mac上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆