问题
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;
}
}
or using Scanner class:
Scanner scanner = new Scanner(socket.getInputStream());
while (scanner.hasNextLine())
{
serverResponce = scanner.nextLine();
if (serverResponce.compareTo(message) == 0) {
break;
}
}
I also tried ready() in BufferedReader or hasNextLine() in Scanner but without any use.
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?
回答1:
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.
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.
来源:https://stackoverflow.com/questions/19623987/java-bufferedreader-works-on-windows-and-not-mac