JavaHTTPServer.java Page 1 import java.io. Batteredoutoetscrear; import java.io.EufferedReader; import java.io.File; imp

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

JavaHTTPServer.java Page 1 import java.io. Batteredoutoetscrear; import java.io.EufferedReader; import java.io.File; imp

Post by answerhappygod »

Javahttpserver Java Page 1 Import Java Io Batteredoutoetscrear Import Java Io Eufferedreader Import Java Io File Imp 1
Javahttpserver Java Page 1 Import Java Io Batteredoutoetscrear Import Java Io Eufferedreader Import Java Io File Imp 1 (88.12 KiB) Viewed 30 times
JavaHTTPServer.java Page 1 import java.io. Batteredoutoetscrear; import java.io.EufferedReader; import java.io.File; import java.io.FileInpu.stream: import java.io.F.leNotFoundException; import java.io.IOException; import java.io. Tapu..st.reamReader; import java.io.outputstream; import java.io. Princwricer; import java...ServerSockel.; import java.net. Socket; import java.util.Date: import java...il.si.ringTokenizeri // The tutorial can be found just here on the ssaurel's Blog: !/ hulps://www.seaurel.com/blog/create-a-simple-h. ... er-in-java 1! Each client connection will be managed in a dedicated Thread public class JavaHTTPServer implements Runnable static final File WEB_ROOS = new File"."); static final String DEFAULT_FILE = "index.html"; static final String LLLL NOT FOUND "404.html", static final String METHOD_NO_SUPPORTED = "not_supported.html"; // port to listen connection static final int POR'I - 8080; // verbose mode static final boolean veroose = true; // client connection via socket class private Socket connect: public JavaHT Pserver (socker c) public Concl. = c; public static void main(String[] args) try { Serversocket serverconnec: new Serversocket (PORT'); System.out.println("Server started. Listening for connections on port : " + PORT + "..\n"); // we listen until user hats server execution while (true) JavaHTTPServer nyserver = new JavaHTTPServer (serverConnect.accept()); if (vercose) System.out.printin("Connecton opened. (" + new Date() - ")"); 1 // create dedicated thread to manage the client connection Thread thread = new Thread (ryserver); Lhread.url.(); } } catch (IOException e) 1 Syslen.art.println("Server Connect or error: " - e.gel.Message());

JavaHTTPServer.java Page 2 Coverride public void run() 17 we manage our gart'cular client connection EufferedReader in - null; Printwriter ou: - null; Baferedoutputstream dataou: - null; suring fileRequested = muli try // we read characters from the client via input stream on the socket in = new BufferedReader (new InputscreamReader (connect.getInputStrean()); // we gel. character culpu.. a.rean lo alian. (for headers out new Erin-wrizer (connect.cetoutputstream()); 7/ get binary cutput stream to client (for requested data) dataOut = new Pufferedont.puts.rearr (connec..geotoutstream()); // get first line of the request from the client String ing.t = in.readLine(); // we parse the request with a string tokenizer StringToke-izer parse = new StringTokenizer (input); string metrod = parse.nex-roken ().topperCase(); // we get the HTTP method of the client // we get tile requested fileRequested = parse.nex-roken ().tolowerCase(); // We spport only GET and HEAD nethods, we check if (!method.equals("SET") ! mechod.cguals("HEAD")) : ܝܺ if (vercos) System.out.printin("501 Not Implemented method +" method."); : // we return the not supported file to the client File lile = new File(WER_ROOT, METHOD_NOT_SUPPORTED); int filelength (int) fie.length(); String contentMimeType = "text/html"; //read content to relurn to client byte'l fleData read leData(file, FileLength); // We send HTTP Headers with data -o client out.println("HITP/1. - 50- Not Implemented"); out.println("Server: Java HTTP Server from SSaurel : 1.0"); out.println("Date: " + new Date()); out.println("Content-tyce: " + contentMime l'ype); out.println("Content-Length: " + fileLength); out.println(); // blank line between headers and content, very important ! out. Flush(); // flush character output stream buffer // file dataout.write(fileData, 0, filelerg=h): dataout.flush(); } else // GET OY HEAD method if (fileRequested. endsh:th("/")) fileaequested + DEFAULI FILE; 1

JavaHTTPServer.java Page 3 File file = new File (WEB_ROOF, fileRequested); int filcLength = (int) flic. length(); ( String content getconten: 'ype (fileRequested); // GET method so we recun concent if (method.equals("GET")) byte[] fileData - readFileData(fils, fileLength); // send HTP Headers out.println("HTTP/1.1 200 OK"); out.println("Server: Java HCP Server From SSaurel : 1.0"); oul..println("Dale: " - new Dale); out.println("Content-type: " + content); + out.println("Content-Length: " + filelength); out.println(); // blank line be.ween headers and conteni, very imporlan out.flus.:(); // flush character output stream buffer t! dataout.writeificeData, 0, FileLength); dataOut.flus... (); : if (vercose) System.out.prinsin("ele" | fileRequested" of type "conten (! | returned"); } } catch (FileNotFoundException fnic) { try fileNotFound (out, dataout, fileRequested); } catch (OExceps-on 10e) System.err.println("Errer with Gile ne. found exception : " + ice.go.Messa ge()); } ) catch (IOException ice) { System.err.println("Server error: " 11 + 1oei } } finally { try in.close(); out.close(); dataout.close(); connect.close(); // we close socket connec-ion } catch (Exception e) System.err.println("Error closing strean :" e.gel.Message()); " ; } if (verbose) System.out.println("Connection closed.\n"); }

JavaHTTPServer.java Page 4 } private bytel. readFi eData (File tile, int filelength) throws TOException PileInputStream fileIn = null; byte[] fileData = new byte.filelangth]; try { fileIn - new FileInputStream(: le); FileIn.read(fileData); } finally { if (rilen ! - null) filein.close(); } return fileData; + // return supported MIME Types private String getConten-Type (String fileReques-es) 1 if (fileRequested.endsWith(".htm" 11 Silekeqsested.endswith(".html"); return "text/html"; else return "text/plain"; private void fileNotFound (Prunthriter out, OutputStrearr. dacaous, String filežequest ed) throws TOFxception { File file new Fiče (VES ROOT, FILE_NOT_FOUND); int filelength = (int) file.length(); suring coal.enl. = "Lex../hl."; byte[] fileDaca - readFileda a file, filelength); oul.println("HTTP/1.1 404 File Not Found"); out.println("Server: Java HIT Server from ssaure: : 1.0"); out.println("Date: " + new Date()); cul.println("Content--ype: " + conler...); out.println("Content-length: " + filelengzh): out.println(); // blank line cetween headers and content, very important ! out.fl.sh(); // flush character output screar buffer dataout.write(tileData, 0, fileLength); dataout.flush(); if (verbose) ( System.out.println("File" } Pilekeqsested " not found");

2 Requirements 1. Use the JavaHTTPServer.java code as a starting base for your project. 2. Your code needs to generate an index file to reflect real-time updates to the filesystem on your computer, upon browser refresh. You may research real webpages to see how they generate their file records upon refresh. Hint: you should be looking for a specific programming language to perform this, such as PHP. 3. The index file will have a very simple structure. See the example above. It will contain: (a) A greyed-out link to the parent directory, when the user is at the root. (b) A click-able link to the parent directory, when the user is not at root. This link takes the user one page above in the directory hierarchy. (c) An html table of three columns: Name, Size, and Date Modified. (d) Each entry in the table will have a click-able link that corresponds to either (I) entering a directory, or (II) downloading a file directly. (e) If the entry corresponds to a directory, the Size column should be blank. (1) If the entry corresponds to a file, the Size column will have the size of the file, in kB, rounded to a single decimal place. 1

(g) The data for the Date Modified column will be the date and time of the last modification of a given entry. (h) The data for all three columns is queried from the operating system in real-time, upon browser refresh. If an item is deleted from the filesystem, when the browser refreshes, it should no longer appear in the website. If a new item is added to the filesystem, when the browser refreshes, it should now appear in the website. (i) In the root directory, there needs to be at least the following: i. Three or more files. ii. Two or more folders. Each folder needs to contain three or more files. For a total of: two folders, and nine files, organized as described above. You will need to include at least one *.txt file, and at least one *.jpg file. (j) You may sort the contents however you would like, or not at all. 4. You do not need to have a domain name. In other words, you can use 127.0.0.1:8080 when accessing the website over localhost. 5. You will need to access this website, navigate through it, and download a file from it, using a remote computer on the same network.

You need to ensure that your website does not have write permissions into your computer. This project should exhibit read permissions only. You may allow your website to exhibit execute permissions as you see fit, depending on how you write your filesystem querying code. 4 What to Turn In 1. Turn in one Word or PDF document, containing the following: (a) State whether or not the project is working overall. (b) State individual features of interest that are working. (c) State features that are not working. (d) Paste screenshots of all of the webpages generated by your code, for your website. (e) Paste the entire code of a fully functioning, fully-generated website, including all *.java code, all *.html code, and anything else, such as *.php code. Note that, for the above, you need to paste both the code that generates the webpages, and the resulting webpages themselves. (f) State the IP address and port number of the computer that is running the server. (g) State a given day, within one week after the project deadline, when you will run this server, from 6AM to 6PM, and I will try to access it remotely. You may alternately schedule a day and time with me to test it in real-time, over a video chat. I will attempt to download the *.jpg file from your website. The *.jpg file should be a picture of something that would fall into your 'personal favorite category. For example, you might post a movie poster of your favorite movie, or of your favorite TV show, or of your favorite music album, or even a photo of your favorite vacation location.
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply