I am doing some benchmarks on a HTTP server. To avoid potential conflict with HTTP libraries, I open the connection directly using a Socket, with no HTTP persistent connections.
The Java code opens and connects an InputStream on a socket connected to a loaded HTTP server. It is running on Linux.
I see that that either of these could happen:
- The socket connect (new Socket()) could take long. This makes sense if the server has a backlog in accepting new connections.
- The socket connect is fast but the delay, up to 1500 milliseconds, is in the last read when read() returns -1 to signify the stream is at the end of “the file.” This I do not understand.
The code follows the standard, with some timing code added:
final byte[] buffer = new byte[8192];
int size = inputStream.read(buffer);
while (size > 0) {
// Copy the buffer
size = inputStream.read(buffer);
}
Assuming that the scenario is exactly as you’ve explained; i.e. that you simply connected to port 80 and tried to read data:
-1from theread(...)call.Basically, your code has to send a well-formed HTTP request to the server if you expect the server to send you a response.
On the other hand, if your code did send a well-formed HTTP request, then the behaviour could be caused by your code trying to read more data that the server has to send … combined with sending a Request that specified a persistent connection (see HTTP 1.1 spec, section 8.1).