{ "key_pair_value_system": true, "answer_rating_count": "", "question_feedback_html": { "html_star": "", "html_star_feedback": "" }, "answer_average_rating_value": "", "answer_date_js": "2024-09-05T21:04:40-04:00", "answer_date": "2024-09-05 21:04:40", "is_docs_available": null, "is_excel_available": null, "is_pdf_available": null, "count_file_available": 0, "main_page": "student_question_view", "question_id": "9227493", "url": "\/study-help\/questions\/web-server-write-a-simple-functional-web-server-capable-of-9227493", "question_creation_date_js": "2024-09-05T21:04:40-04:00", "question_creation_date": "Sep 05, 2024 09:04 PM", "meta_title": "[Solved] Web Server write a simple functional web | SolutionInn", "meta_description": "Answer of - Web Server write a simple functional web server capable of sending files to a web browser on request. The web server m | SolutionInn", "meta_keywords": "web,server,write,simple,functional,capable,sending,files,browser,request,create,listening", "question_title_h1": "Web Server write a simple functional web server capable of sending files to a web browser on request. The web server must create a listening", "question_title": "Web Server write a simple functional web server capable of sending files", "question_title_for_js_snippet": "Web Server write a simple functional web server capable of sending files to a web browser on request The web server must create a listening socket and accept connections must implement enough of the HTTP 1 1 protocol to enable it to read requests for files and to send the requested files should also send error responses to client when appropriate new Eclipse project and create your main program class The basic programming for a server is pretty standard It just has to create a ServerSocket and use it to accept connection requests For the main routine in your program, you can just use the main routine from ReadRequest java copy and paste it from here public static void main(String args) ServerSocket serverSocket try serverSocket new ServerSocket(LISTENING PORT) catch (Exception e) System out println( Failed to create listening socket ) return System out println( Listening on port LISTENING PORT) try while (true) Socket connection serverSocket accept() System out println( Connection from connection getRemoteSocketAddress()) handleConnection(connection) catch (Exception e) System out println( Server socket shut down unexpectedly ) System out println( Error e) System out println( Exiting ) The problem is to write the handleConnection() method This method gets an already connected socket as a parameter It can use that socket to get an InputStream and an OutputStream for communicating over the connection It can read the request from the input stream and send a response to the output stream Finally, it can close the connection You can use some ideas (and maybe some code) from the handleConnection method in ReadRequest java, but the method that you are writing will be a good deal more complicated very important 1 the handleConnection method should catch and handle any exception that occurs so that the exception does not crash the whole server and 2 the socket must be closed at the end of the method Use a try catch finally statement to make sure that 1 and 2 are done correctly ReadRequest java example program is ready to send error responses to client, and fulfilling legitimate requests next implement error handling simply return from the handleConnection method when you detect an error first three tokens that you read from the input stream should be GET the path to the file that is being requested and HTTP 1 1 or just possibly HTTP 1 0 If you can't read three tokens, or if they are not of the expected form, you should consider that to be an error Assuming request has the correct form try to find the requested file and send it in a response over the output stream the files that are available on your server should be in some directory, which is called the root directory of the server use any directory that you want as your root directory as long as you can read that directory could also use your own www directory Assuming rootDirectory is the root directory of your server and pathToFile is the path to the file as given in the request from the browser, then the full name of the file is rootDirectory pathToFile, and you can create a File object to represent the file that is being requested as follows File file new File(rootDirectory pathToFile) Note the method file exists() can be used to check whether the requested file actually exists the method file isDirectory() tests whether the file is actually a directory rather than a regular file the method file canRead() tests whether you can read the file the method file length() tells you the length of the file, that is, how many bytes of data it contains Once having file and know that it is a regular file and that you can read it, send a response to the browser If the file is a directory, you can't send it, but a typical server, in this case, will send the contents of a file named index html in that directory, if it exists think about how to implement this if you want Before you send the file, send the status line, some headers, and an empty line use a PrintWriter to do this However, the HTTP protocol specifies that ends of line should be indicated by rather than the that is standard in Linux Although I have found that it doesn't matter when sending text documents, it does seem to matter when sending images So, instead of using out println(x), you should use out print(x ) to send a line of text, and use out print( ) to send a blank line The status line to indicate a good response should be HTTP 1 1 200 OK (with at the end) You should send three headers Connection , Content Length , and Content Type For the Connection header, you can send Connection close which informs the browser to close the connection after sending the file The Content Length header should specify the number of bytes in the file, which you can find with the file length() method The Content Type header tells the browser what kind of data is in the file It can generally be determined from the extension part of the file name Here is a method that will return the proper content type for many kinds of files private static String getMimeType(String fileName) int pos fileName lastIndexOf(' ') if (pos 0) no file extension in name return x application x unknown String ext fileName substring(pos 1) toLowerCase() if (ext equals( txt )) return text plain else if (ext equals( html )) return text html else if (ext equals( htm )) return text html else if (ext equals( css )) return text css else if (ext equals( js )) return text javascript else if (ext equals( java )) return text x java else if (ext equals( jpeg )) return image jpeg else if (ext equals( jpg )) return image jpeg else if (ext equals( png )) return image png else if (ext equals( gif )) return image gif else if (ext equals( ico )) return image x icon else if (ext equals( class )) return application java vm else if (ext equals( jar )) return application java archive else if (ext equals( zip )) return application zip else if (ext equals( xml )) return application xml else if (ext equals( xhtml )) return application xhtml xml else return x application x unknown Note x application x unknown is something made up it will probably make the browser offer to save the file the beginning of the response might look something like HTTP 1 1 200 OK Connection close Content Type text html Content Length 3572 with a blank line at the end And don't forget to flush the PrintWriter after sending this data time to send the data from the file itself The file is not necessarily text, and in any case it should be sent as a stream of bytes The following method can be used to copy the content of the file to the socket's output stream private static void sendFile(File file, OutputStream socketOut) throws IOException InputStream in new BufferedInputStream(new FileInputStream(file)) OutputStream out new BufferedOutputStream(socketOut) while (true) int x in read() read one byte from file if (x 0) break end of file reached out write(x) write the byte to the socket out flush() your web server program should work for legal requests for valid files you can try telnetting to your server and sending it a request, to see what response it actually sends Error Handling If something goes wrong with a request, the server should nevertheless send a response The first line of a response always contains a status code indicating the status of the response, as well as a textual description of the status For a normal response, the status code is 200, indicating success Status codes for errors are in the 400s and 500s For example, the status code 404 is used when the request asks for a file that does not exist on the server The first line of the response, in this case, is HTTP 1 1 404 Not Found The response should also include, at least, a Content type header and the content of the page that is to be displayed in the browser to inform the user of the error For example, the complete response for a 404 error might look like HTTP 1 1 404 Not Found Connection close Content Type text html Error Error 404 Not Found The resource that you requested does not exist on this server could also use content type of text plain , and send the response using plain text rather than HTML I suggest static void sendErrorResponse(int errorCode, OutputStream socketOut) to send error responses I suggest this method catch any exceptions that occur and do nothing since there's really nothing reasonable to do if an error occurs while you are trying to send an error message this method should not be called if you already started to send a 200 OK response or another error response if an error occurs at that point, it's probably an unrecoverable network error, and you might as well just end the handleConnection method Also, remember to exit handleConnection after sending the error response don't try to continue processing after an error Here are some error responses that your program might want to send You should at least be able to send 404 and 501 HTTP 1 1 404 Not Found discussed above HTTP 1 1 403 Forbidden you could send this if the requested file exists, but you don't have permission to read it or just send 404 HTTP 1 1 400 Bad Request you could send this if the syntax of the request is bad, for example if the third token is not HTTP 1 1 or HTTP 1 0 or just send 501 or 500 HTTP 1 1 501 Not Implemented if the method in the request in anything other than GET HTTP 1 1 500 Internal Server Error you could send this if you catch some unexpected error in the handleConnection method your server should work pretty well with a web browser Threads The server that you have written is single threaded It can only handle one request at a time If a second request comes in while you are working on another request, the second request will have to wait until you are finished with the first request, even if that takes a long time because you are sending a large file over a slow network This is not acceptable for a real server A real server should be multi threaded, with several threads to handle connections An easy way to write a multi threaded server is to start a new thread to handle each connection request New requests can be handled as they arrive, even if previous requests are still being handled by other threads this solution is still not acceptable for real servers, because starting a new thread is a relatively time consuming thing, and because you don't want to have the possibility of having too many threads running at the same time To make your server into a multi threaded server, you will need a subclass of Thread The class needs a run() method to specify the task that the thread will perform In this case, it should handle one connection request We can pass the socket for that connection to the constuctor of the class the class Copy into program private static class ConnectionThread extends Thread Socket connection ConnectionThread(Socket connection) this connection connection public void run() handleConnection(connection) the main routine, instead of calling handleConnection directly, create and start a thread of type ConnectionThread ConnectionThread thread new ConnectionThread(connection) thread start() With this change, you should have a minimal but functional multi threaded web server", "question_description": "

<\/p>

Web Server<\/strong><\/p>

write a simple functional web server capable of sending files to a web browser on request. The web server must create a listening socket and accept connections. must implement enough of the HTTP\/1.1 protocol to enable it to read requests for files and to send the requested files. should also send error responses to client when appropriate<\/p>

new Eclipse project and create your main program class. The basic programming for a server is pretty standard It just has to create a ServerSocket and use it to accept connection requests. For the main routine in your program, you can just use the main routine from ReadRequest.java copy-and-paste it from here<\/p>

<\/p>

public static void main(String[] args) {<\/p>

ServerSocket serverSocket;<\/p>

try {<\/p>

serverSocket = new ServerSocket(LISTENING_PORT);<\/p>

}<\/p>

catch (Exception e) {<\/p>

System.out.println(\"Failed to create listening socket.\");<\/p>

return;<\/p>

}<\/p>

System.out.println(\"Listening on port \" + LISTENING_PORT);<\/p>

try {<\/p>

while (true) {<\/p>

Socket connection = serverSocket.accept();<\/p>

System.out.println(\" Connection from \"<\/p>

+ connection.getRemoteSocketAddress());<\/p>

handleConnection(connection)<\/p>

catch (Exception e) {<\/p>

System.out.println(\"Server socket shut down unexpectedly!\");<\/p>

System.out.println(\"Error: \" + e);<\/p>

System.out.println(\"Exiting.\");<\/p>

The problem is to write the handleConnection() method. This method gets an already connected socket as a parameter. It can use that socket to get an InputStream and an OutputStream for communicating over the connection. It can read the request from the input stream and send a response to the output stream. Finally, it can close the connection. You can use some ideas (and maybe some code) from the handleConnection method in ReadRequest.java, but the method that you are writing will be a good deal more complicated.<\/p>

very important<\/p>

1 the handleConnection method should catch and handle any exception that occurs so that the exception does not crash the whole server and<\/p>

2 the socket must be closed at the end of the method. Use a try..catch..finally statement to make sure that 1 and 2 are done correctly. ReadRequest.java example<\/p>

program is ready to send error responses to client, and fulfilling legitimate requests. next implement error-handling. simply return from the handleConnection method when you detect an error<\/p>

first three tokens that you read from the input stream should be GET the path to the file that is being requested and HTTP\/1.1 or just possibly HTTP\/1.0 If you can't read three tokens, or if they are not of the expected form, you should consider that to be an error<\/p>

Assuming request has the correct form try to find the requested file and send it in a response over the output stream. the files that are available on your server should be in some directory, which is called the root directory of the server. use any directory that you want as your root directory as long as you can read that directory<\/p>

could also use your own www directory. Assuming rootDirectory is the root directory of your server and pathToFile is the path to the file as given in the request from the browser, then the full name of the file is rootDirectory + pathToFile, and you can create a File object to represent the file that is being requested as follows<\/p>

File file = new File(rootDirectory + pathToFile);<\/p>

Note<\/p>

the method file.exists() can be used to check whether the requested file actually exists<\/p>

the method file.isDirectory() tests whether the file is actually a directory rather than a regular file<\/p>

the method file.canRead() tests whether you can read the file<\/p>

the method file.length() tells you the length of the file, that is, how many bytes of data it contains<\/p>

Once having file and know that it is a regular file and that you can read it, send a response to the browser. If the file is a directory, you can't send it, but a typical server, in this case, will send the contents of a file named index.html in that directory, if it exists. think about how to implement this if you want. Before you send the file, send the status line, some headers, and an empty line. use a PrintWriter to do this. However, the HTTP protocol specifies that ends-of-line should be indicated by \" \" rather than the \" \" that is standard in Linux. Although I have found that it doesn't matter when sending text documents, it does seem to matter when sending images. So, instead of using out.println(x), you should use out.print(x + \" \") to send a line of text, and use out.print(\" \") to send a blank line. The status line to indicate a good response should be HTTP\/1.1 200 OK<\/p>

(with \" \" at the end). You should send three headers: \"Connection\", \"Content-Length\", and \"Content-Type\". For the Connection header, you can send<\/p>

Connection close<\/p>

which informs the browser to close the connection after sending the file. The Content-Length header should specify the number of bytes in the file, which you can find with the file.length() method. The Content-Type header tells the browser what kind of data is in the file. It can generally be determined from the extension part of the file name. Here is a method that will return the proper content type for many kinds of files<\/p>

private static String getMimeType(String fileName) {<\/p>

int pos = fileName.lastIndexOf('.');<\/p>

if (pos < 0) \/\/ no file extension in name<\/p>

return \"x-application\/x-unknown\";<\/p>

String ext = fileName.substring(pos+1).toLowerCase();<\/p>

if (ext.equals(\"txt\")) return \"text\/plain\";<\/p>

else if (ext.equals(\"html\")) return \"text\/html\";<\/p>

else if (ext.equals(\"htm\")) return \"text\/html\";<\/p>

else if (ext.equals(\"css\")) return \"text\/css\";<\/p>

else if (ext.equals(\"js\")) return \"text\/javascript\";<\/p>

else if (ext.equals(\"java\")) return \"text\/x-java\";<\/p>

else if (ext.equals(\"jpeg\")) return \"image\/jpeg\";<\/p>

else if (ext.equals(\"jpg\")) return \"image\/jpeg\";<\/p>

else if (ext.equals(\"png\")) return \"image\/png\";<\/p>

else if (ext.equals(\"gif\")) return \"image\/gif\";<\/p>

else if (ext.equals(\"ico\")) return \"image\/x-icon\";<\/p>

else if (ext.equals(\"class\")) return \"application\/java-vm\";<\/p>

else if (ext.equals(\"jar\")) return \"application\/java-archive\";<\/p>

else if (ext.equals(\"zip\")) return \"application\/zip\";<\/p>

else if (ext.equals(\"xml\")) return \"application\/xml\";<\/p>

else if (ext.equals(\"xhtml\")) return\"application\/xhtml+xml\";<\/p>

else return \"x-application\/x-unknown\";<\/p>

\/\/ Note: x-application\/x-unknown is something made up;<\/p>

\/\/ it will probably make the browser offer to save the file.<\/p>

the beginning of the response might look something like<\/p>

HTTP\/1.1 200 OK<\/p>

Connection: close<\/p>

Content-Type: text\/html<\/p>

Content-Length: 3572<\/p>

with a blank line at the end And don't forget to flush the PrintWriter after sending this data<\/p>

time to send the data from the file itself The file is not necessarily text, and in any case it should be sent as a stream of bytes. The following method can be used to copy the content of the file to the socket's output stream<\/p>

private static void sendFile(File file, OutputStream socketOut) throws<\/p>

IOException {<\/p>

InputStream in = new BufferedInputStream(new FileInputStream(file));<\/p>

OutputStream out = new BufferedOutputStream(socketOut);<\/p>

while (true) {<\/p>

int x = in.read(); \/\/ read one byte from file<\/p>

if (x < 0)<\/p>

break; \/\/ end of file reached<\/p>

out.write(x); \/\/ write the byte to the socket<\/p>

}<\/p>

out.flush();<\/p>

your web server program should work for legal requests for valid files. you can try telnetting to your server and sending it a request, to see what response it actually sends<\/p>

Error Handling<\/p>

If something goes wrong with a request, the server should nevertheless send a response. The first line of a response always contains a status code indicating the status of the response, as well as a textual description of the status. For a normal response, the status code is 200, indicating success. Status codes for errors are in the 400s and 500s. For example, the status code 404 is used when the request asks for a file that does not exist on the server. The first line of the response, in this case, is \"HTTP\/1.1 404 Not<\/p>

Found\". The response should also include, at least, a \"Content-type\" header and the content of the page that is to be displayed in the browser to inform the user of the error. For example, the complete response for a 404 error might look like<\/p>

HTTP\/1.1 404 Not Found<\/p>

Connection: close<\/p>

Content-Type: text\/html<\/p>

<\/p>

Error<\/title><\/head><body><\/p> <p><h2>Error: 404 Not Found<\/h2><\/p> <p><p>The resource that you requested does not exist on this server.<\/p><\/p> <p><\/body><\/html><\/p> <p> <\/p> <p>could also use content type of \"text\/plain\", and send the response using plain text rather than HTML. I suggest<\/p> <p>static void sendErrorResponse(int errorCode, OutputStream socketOut)<\/p> <p>to send error responses. I suggest this method catch any exceptions that occur and do nothing since there's really nothing reasonable to do if an error occurs while you are trying to send an error message. this method should not be called if you already started to send a \"200 OK\" response or another error response if an error occurs at that point, it's probably an unrecoverable network error, and you might as well just end the handleConnection method. Also, remember to exit handleConnection after sending the error response; don't try to continue processing after an error<\/p> <p>Here are some error responses that your program might want to send. You should at least be able to send 404 and 501<\/p> <p>HTTP\/1.1 404 Not Found discussed above<\/p> <p>HTTP\/1.1 403 Forbidden you could send this if the requested file exists, but you don't have permission to read it or just send 404<\/p> <p>HTTP\/1.1 400 Bad Request you could send this if the syntax of the request is bad, for example if the third token is not \"HTTP\/1.1\" or \"HTTP\/1.0\" or just send 501 or 500<\/p> <p>HTTP\/1.1 501 Not Implemented if the method in the request in anything other than GET<\/p> <p>HTTP\/1.1 500 Internal Server Error you could send this if you catch some unexpected error in the handleConnection method<\/p> <p>your server should work pretty well with a web browser<\/p> <p>Threads<\/p> <p>The server that you have written is single-threaded. It can only handle one request at a time. If a second request comes in while you are working on another request, the second request will have to wait until you are finished with the first request, even if that takes a long time because you are sending a large file over a slow network. This is not acceptable for a real server. A real server should be multi-threaded, with several threads to handle connections<\/p> <p>An easy way to write a multi-threaded server is to start a new thread to handle each connection request. New requests can be handled as they arrive, even if previous requests are still being handled by other threads. this solution is still not acceptable for real servers, because starting a new thread is a relatively time-consuming thing, and because you don't want to have the possibility of having too many threads running at the same time<\/p> <p>To make your server into a multi-threaded server, you will need a subclass of Thread. The class needs a run() method to specify the task that the thread will perform. In this case, it should handle one connection request. We can pass the socket for that connection to the constuctor of the class. the class. Copy into program<\/p> <p> private static class ConnectionThread extends Thread {<\/p> <p> Socket connection;<\/p> <p> ConnectionThread(Socket connection) {<\/p> <p> this.connection = connection;<\/p> <p> }<\/p> <p> public void run() {<\/p> <p> handleConnection(connection)<\/p> <p> <\/p> <p> the main routine, instead of calling handleConnection directly, create and start a thread of type ConnectionThread<\/p> <p>ConnectionThread thread = new ConnectionThread(connection);<\/p> <p>thread.start();<\/p> <p> With this change, you should have a minimal but functional multi-threaded web server<\/p> <p> <\/p> <p> <\/p>", "transcribed_text": "", "related_book": { "title": null, "isbn": null, "edition": null, "authors": null, "cover_image": null, "uri": null, "see_more_uri": "" }, "free_related_book": { "isbn": "", "uri": "", "name": "", "edition": "" }, "question_posted": "2024-09-05 21:04:40", "see_more_questions_link": null, "step_by_step_answer": "The Answer is in the image, click to view ...", "students_also_viewed": [ { "url": "\/study-help\/introduction-to-probability-statistics\/10118-arranging-objects-the-following-data-are-the-response-times-1986529", "description": "10.118 Arranging Objects The following data are the response times in seconds for n = 25 first graders to arrange three objects by size. Find a 95% confidence interval for the average re- sponse time...", "stars": 0 }, { "url": "\/find-the-following-financial-ratios-for-smolira-golf-corp-use", "description": "Find the following financial ratios for Smolira Golf Corp. (use year-end figures rather than average values where appropriate): Short-term solvency ratios: a. Current...", "stars": 3.5 }, { "url": "\/study-help\/questions\/got-those-numbers-wrong-i-will-give-upward-if-u-9958513", "description": "got those numbers wrong, I will give upward if u do them right Exercise 18.5 (Algo) Computing Costs per Equivalent Unit (LO18-2, LO18-3, LO18-4, LO18-5) Old Victrola, Inc. produces top-quality...", "stars": 3.5 }, { "url": "\/study-help\/questions\/show-the-different-arguments-put-forward-by-the-proponents-and-9735824", "description": "Show the different arguments put forward by the proponents and opponents of currency hedging", "stars": 3.5 }, { "url": "\/study-help\/questions\/answer-management-interview-questions-1describe-your-skills-knowledge-and-experience-1008763", "description": "answer management interview questions 1-Describe your skills, knowledge, and experience in managing office policies and procedures, such as developing and implementing project proposals, budgets, or...", "stars": 3.5 }, { "url": "\/study-help\/questions\/once-a-strategy-for-performance-improvement-has-been-determined-how-1004508", "description": "Once a strategy for performance improvement has been determined, how can organizations gain the long-term commitment and investment of time required by all levels of the organization to implement the...", "stars": 3.5 }, { "url": "\/study-help\/questions\/what-makes-the-store-manager-of-a-retail-company-a-1004985", "description": "What makes the store manager of a retail company a classic example of an operations manager. Hint: please refer to large retail companies", "stars": 3.5 }, { "url": "\/study-help\/questions\/consider-the-following-workplace-research-example-within-one-company-division-1004664", "description": "Consider the following workplace research example: Within one company division, employees were asked to create self-managed work groups in order to accomplish an important company objective. Leaders...", "stars": 3.5 }, { "url": "\/study-help\/questions\/define-and-describe-the-types-of-manufacturing-services-and-extraction-1004647", "description": "Define and describe the types of manufacturing, services, and extraction industries. Give examples. 2. What are the various categories of services? Give examples for each category? 3. How do services...", "stars": 3.5 } ], "next_back_navigation": { "previous": "\/study-help\/questions\/a-borrower-takes-out-a-15year-mortgage-loan-for-365859-9227492", "next": "\/study-help\/questions\/kenneths-arrows-and-bows-borrow-10000-for-one-year-at-9227494" }, "breadcrumbs": [ { "name": "Study help", "link": "https:\/\/www.solutioninn.com\/study-help\/questions-and-answers" }, { "name": "Computer Science", "link": "https:\/\/www.solutioninn.com\/study-help\/questions-and-answers\/computer-science" }, { "name": "Databases", "link": "https:\/\/www.solutioninn.com\/study-help\/questions\/computer-science-databases" }, { "name": "Web Server write a simple functional web server capable of sending files", "link": "https:\/\/www.solutioninn.com\/study-help\/questions\/web-server-write-a-simple-functional-web-server-capable-of-9227493" } ], "skill_details": { "skill_id": "656", "skill_name": "Databases", "parent_id": "8" } }