As a task, I implemented a basic web server in Java. When I open raw InputStream , I immediately go to block reading, which reads all 400 or bytes of the HTTP request into an array of bytes. This works, however, I do not check any more data and just close the socket after sending the response.
I am wondering if there is a more reliable way to do this so as not to miss any data from the client. I thought about reading one byte at a time until read returned the end of the stream. However, instead, it blocks when there is no more data, and it is vague that JavaDocs for public abtract int InputStream.read() says:
If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
Thus, this means that two things are possible if the end of the stream is reached: return -1 and lock. I see a lock.
My question is: with a protocol like HTTP, how should you read from the socket and how do you know when all the data that you will receive in connection with this?
source share