Recommended way to read from socket in HTTP server

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?

+4
source share
1 answer

You are quoting JavaDoc: does not imply that two things are possible if the end of the stream is reached. It does not say that blocks read when the end of the stream is detected, but until the end of the stream is detected. After its discovery -1 is returned.

This explains the behavior you observe: no end of the stream is detected, and reading is blocked. The end of the stream is detected after the connection is closed, but it does not close, because the client does not close the connection immediately after sending the request. He must keep it open for an answer.

To ensure that all data is received from the client, you must analyze your HTTP request until you see the end of the header (double new line), as well as any amount of data that they indicated in the header (if any).

If you want to avoid blocking, look at java.nio and channels ( SocketChannel in particular).

+6
source

Source: https://habr.com/ru/post/1399500/


All Articles