About BufferedReader
I am trying to build a mini webserver. The program below suppose to displayed the request of the client in the console, and wait for another connection...but it seems to block at
sContent = sockInput.readLine();
it seems to me that I am not using a correct approach to print the entire request from the client to the console, reason maybe the bufferedreader will not return null if there is nothing to read and simply will block there. Am I right?
What is the correction approach to display the request of the client to the console(by using bufferedreader) and not blocking at the middle if there is nothing to read?
public class Test {
public static void main(String args[]) throws Exception {
ServerSocket serverSocket = new ServerSocket(10000);
while (true) {
Socket sock = serverSocket.accept();//Wait for connection
BufferedReader sockInput = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
String sContent = sockInput.readLine();
while (sContent != null) {
System.out.println("here="+sContent);
sContent = sockInput.readLine();//<--Block here
}
sock.close();
}
}
}
[1213 byte] By [
jack0348a] at [2007-11-26 19:19:19]

In the HTTP protocol, the browser sends an empty line after the request headers. readLine() won't give null, it will give an empty line; check for that and break out of the loop.
If the request is a HTTP POST, there may be additional data after the empty line (the POST parameters). The "Content-Length" header will tell how much of data there are.
If you think about it a little it may dawn on you why readLine blocks instead of returning null.
Why would it return null? Answer: When it detects that the end of the stream has been reached.
How can it determine if the end of the stream has been reached for socket communications? Answer: It can't. It may be that the sender just hasn't sent the next chunk of bytes while the recipient is waiting for them, so it blocks waiting for something to be sent.
This is why this type of stream needs a protocol in the communications -- something in the data itself to "tell" the recipient there's no more data.
For streams connected to files (FileInputStream), it's a different animal. It can tell when it's at the end of the stream, because it's tied to a file which has a size.
Similarly, for streams connected to other resources of known sizes, such as a ByteArrayInputStream, it would know when it's at the end of the stream. In those cases, readLine can return null rather than block waiting for something (more input) that's never going to happen.
And actually it isn't readLine itself which is blocking, it's a call to one of the underlying stream's read methods which is blocking rather than returning a value which means "no more data".