Xu Chen Xu Chen - 3 months ago 9
HTTP Question

Why scanner.hasNext() blocks when reading Http Request

I am writing a server that receives http request(only GET method as part of simplification from school work)

I used

Socket
class to get the connection
I then used
InputStream
as well as
Scanner
to read the http request.

However, while I was reading the http request headers line by line using
hasNext()
. The program hangs at
hasNext()
, waiting for more inputs even it has consumed all the lines.

Below is my
readRequest
method:


public void readRequest(Socket client) throws BadRequestException {
StringBuilder builder = new StringBuilder();

try {
Scanner sc = new Scanner(client.getInputStream());
sc.useDelimiter("\\r\\n");

while(sc.hasNext()){
builder.append(sc.next());
builder.append("\n");
}

parseRequestFromClient(builder.toString());
} catch (IOException e) {
throw new BadRequestException(e.getMessage());
}

Answer

Your facing this issue because hasNext will behind the scene read the source to check if there is another matching token until the source reaches its end by returning -1 which is not not your case here.

As reminder here is the Javadoc of the method hasNext:

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.


You should avoid reinventing the wheel and use a library that will do it for you, like DavidWebb and many others.