Questions
Please write a web server that is capable of sending files to a web browser on request. The web server creates a listening socket and accepts connections. It implements just enough of the HTTP/1.1 protocol to enable it to read requests for files and to send the requested files. It is also capable of sending error responses to the client when appropriate.
1. Instructions for use
To test this program, you need to change the value of variable rootDirectory in the code to the directory where you store the test files. I use “F:” in my code, and you can change it. Then put the test files in the directory you choose, and then enter the corresponding URL in the browser, for example, using http://localhost:50505/text.txt to ask for a text.txt file from the server. Besides, you can find the test files in the attachment, which contains a text.txt file and a directory with an index.html.
2. Programs and Test Files
2.1. WebServer.java
1 | import java.io.*; |
2.2. Test files
Please click here to download the test files.
3. Outputs
3.1. Case 1
Use the browser to send a request to the server, and ask for the text.txt file. After the server receives the request, it returns the text.txt file to the browser, and the browser displays the content of text.txt
The outputs of the browser:
The outputs of the WebServer program:
3.2. Case 2
Use the browser to send a request to the server, but the path in the file is a directory instead of a file. After the server receives the request, it returns the index.html file in that directory to the browser, and the browser displays the content of the index.html
The outputs of the browser:
The outputs of the WebServer program:
3.3. Case 3
Use the browser to send a request to the server, but if the path is illegal or the file does not exist, the server returns a 404 error and the corresponding HTML file to the browser, and the browser displays the content of the HTML file.
The outputs of the browser:
The outputs of the WebServer program:
3.4. Case 4
For other error types, such as 501 error, which means that the method in the request is not “GET”, we need to use telnet to test. My specific approach is to use the command (telnet localhost 50505) to connect to the server WebServer, and then enter the command (POST /text.txt HTTP/1.1). Because the method in the request header is “POST” instead of “GET“, the server will return a 501 error and the corresponding HTML, and then the telnet side will display the content of the HTML.
The outputs of the telnet:
The outputs of the WebServer program: