HTTP simple server implemented in java

Source: Internet
Author: User
Tags date now

HTTP simple server implemented in java

The program is a little BUG. Thank you for your advice. Why is the difference between different browsers so big?

After running the server program, enter the following request path in the browser to observe the effect (the default path of my server resources is F:/project directory ).

 

/** Simulate the implementation of an HTTP server * the client (browser) requests the Server File, the server program accepts the connection and processes it, and writes the corresponding data to the socket, send to client * This Web Server puts the inbound connection into the pool, and a RequestProcessor class instance removes the connection from the pool and processes it */import java. io. *; import java.net. *; public class JHTTP extends Thread {private File documentRootDirectory; private String indexFileName=index.html; private ServerSocket server; private int numThreads = 50; // set the number of threads started by the server public JHTTP (File documentRootDirectory, int port, String in DexFileName) throws IOException {if (! DocumentRootDirectory. isDirectory () {throw new IOException (documentRootDirectory + does not exist as a directorytransfertransferdomainthis.doc umentRootDirectory = documentRootDirectory; this. indexFileName = indexFileName; this. server = new ServerSocket (port);} public JHTTP (File documentRootDirectory, int port) throws ioexceptionjavasthis(documentrootdirectory,port,index.html);} public JHTTP (File documentRootDirectory) throws success);} public void run () {// enable the request processing thread. This thread extracts a socket connection from the socket pool for data transmission (int I = 0; I
 
  
// The Thread class for processing the connection is import java. util. date; import java. util. using list; import java. util. list; import java. util. stringTokenizer; import java. io. *; import java.net. socket; public class RequestProcessor implements Runnable {private static List pool = new jsonlist (); private File documentRootDirectory; private String indexFileName = index.html; public RequestProcessor (File documentRootDirectory, String indexFileName) {If (documentRootDirectory. isFile () {throw new partition (documentRootDirectory must be a directory, not a file=%%this.doc umentRootDirectory = documentRootDirectory; // return the standard form of this abstract path name. try using this.doc umentRootDirectory = documentRootDirectory. getCanonicalFile ();} catch (IOException e) {System. out. println (e);} if (indexFileName! = Null) {this. indexFileName = indexFileName;} public static void processRequest (Socket request) {// puts the socket connection corresponding to each client into the pool and notifies the thread to process them synchronized (pool) {pool. add (pool. size (), request); pool. policyall () ;}@ Overridepublic void run () {// run the security check. the requested document cannot exceed the root directory String root = documentRootDirectory. getPath (); // because the thread pool policy is used, the thread must be executed continuously to process the connection in the client's request pool (socket pool) while (true) {Socket connection; synchronized (pool) {while (pool. isEmpty () {try {pool. wait ();} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} connection = (Socket) pool. remove (0);} // use the socket intermediary to exchange data between the Server Client. try {OutputStream raw; raw = new BufferedOutputStream (connection. getOutputStream (); Writer out = new OutputStreamWriter (raw); Reader in = new InputStreamReader (new BufferedInputStream (connection. getInputStream (), ASCII); // stores the first row of data requested by the client, StringBuffer requestLine = new StringBuffer (); int c; while (true) {c = in. read (); if (c = ''| c ='') break; requestLine. append (char) c);} String get = requestLine. toString (); System. out. println (get); // record the first line of the request (to break down the first line, as shown below) StringTokenizer st = new StringTokenizer (get); String method = st. nextToken (); String version =; // in this case, only the GET request String filename; String contentType; if (method. equals (GET) {filename = st. nextToken (); if (filename. endsWith (/) filename + = indexFileName; contentType = guessContentTypeFromName (filename); if (st. hasMoreTokens () {version = st. nextToken ();} File theFile = new File (documentRootDirectory, filename. substring (1, filename. length (); if (theFile. canRead () & theFile. getCanonicalPath (). startsWith (root) {DataInputStream FD = new DataInputStream (new BufferedInputStream (new FileInputStream (theFile); byte [] theData = new byte [(int) theFile. length ()]; FCM. readFully (theData); Sox. close (); if (version. startsWith (HTTP) {// send the MIME header out. write (HTTP/1.0 200 OK); // The Header Format stipulated by the HTTP protocol, that is, the line feed is required by the carriage return, it must be Date now = new Date (); out. write (Date: + now +); out. write (Server: JHTTP/1.0); out. write (Content-Length: + theData. length +); out. write (Content-Type: + contentType +); out. flush (); // remember to refresh at the end, write the remaining data in the buffer} // send the actual request file (which may be an image or another binary file) raw. write (theData); raw. flush ();} else {// the file if (version. startsWith (HTTP) {// send the MIME header out. write (HTTP/1.0 404 File Not Found ON MyServer); // The Header Format stipulated by the HTTP protocol, that is, to press enter to wrap, it must be Date now = new Date (); out. write (Date: + now +); out. write (Server: JHTTP/1.0); out. write (Content-Type: text/html);} out. write (
); Out. write ( ); Out. write (); out. write (); out. write (HTTP Error 404: File not found); out. write (); out. flush () ;}} else {// if (version. startsWith (HTTP) {// send the MIME header out. write (HTTP/1.0 501 Not Implemented); // The Header Format stipulated by the HTTP protocol, that is, to press enter to wrap, it must be Date now = new Date (); out. write (Date: + now +); out. write (Server: JHTTP/1.0); out. write (Content-Type: text/html);} out. write (); out. write ( ); Out. write (); out. write (); out. write (HTTP Error 501: Not Implemented); out. write (); out. flush () ;}} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} finally {try {connection. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}} public static String guessContentTypeFromName (String name) {if needed) | name.endsWith(.html) {return text/html;} else if (name.endsWith(.txt) | name. endsWith (. java) {return text/plain;} else if (name. endsWith (. class) {return application/octet-stream;} else if (name.endsWith(.gif) {return image/gif;} else if (name.endsWith(.jpg) | name.endsWith(.jpeg) {return image/jpeg ;} else if (name.endswith(objects) {return audio/mpeg;} else {return text/plain ;}}}



 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.