I wrote a HttpServer, here is the code snippet:
As the snapshot marked, it can't work:
This is the result when I visit the HttpServer by browser:
I do not know what causes it, anybody could help me?
Thanks
I wrote a HttpServer, here is the code snippet:
As the snapshot marked, it can't work:
This is the result when I visit the HttpServer by browser:
I do not know what causes it, anybody could help me?
Thanks
No, an InputStream will return -1 when the socket is closed. End of stream means "End of File" ie. closed connection. It doesn't mean "no data read".
The socket is likely still open, so your code is blocking for the next request and never returning a -1. It will not return until either more data arrives, or the stream is closed.
The request is probably an HTTP 1.1 request. With HTTP 1.1, the socket will stay open to allow reuse of the connection, unless your server decides not to honor it, or the web browser decides to close it. The point of HTTP 1.1 is to allow multiple HTTP requests to pipeline on a single TCP stream connection, and avoid the overhead of build/teardown.
A socket can stay open, but idle with no data for a long time, so if you try to read from it with a blocking call, your code will hang. The Java InputStream.read() call will block, because it cannot return 0, since 0 is a valid byte value. I recommend that you switch to an alternate read() form, in any case.
Finally, if you are going to write an HTTP server, you shouldn't be using end of stream as your only method of managing the incoming request, you need to parse or scan the request for a legally formed HTTP request, and once received, serve a response, then close the connection. As it is, your current approach doesn't know if/when the HTTP response is well-formed or complete.
Refer to online RFC of the HTTP protocol for the format of a legal request. Request lines end in CR-LF (carriage return + linefeed). You read the 1st line as the request (command), and then a single empty line (CR-LF only), then any HTTP headers will be 1 per line, and when you receive the next empty line, it is the end of the request. You should at minimum issue a "Connection: close" header if you intend to close the socket. Otherwise the client may think your server can handle pipelined requests.
It doesn't make sense to read the input until EOS and then expect to be able to write a response back to the same connection.
You haven't actually written anything like an 'simple HTTP server yet. You need to study the HTTP RFC, in particular the part about content-length of requests. They are delimited by length, not by end of stream.