Java-implemented HTTP simple server

Source: Internet
Author: User

Program a bit bug, welcome expert guidance, why different browser difference so big?

After running the server-side program, enter the following request path observation in the browser (the default path for my server resource is set to the F:/project directory).

http://localhost

Http://localhost/myfile.txt

/* * Simulate an implementation of an HTTP server * Client (browser) requests the server's files, the server-side program accepts the connection and processing, writes the corresponding data to the socket, sends to the client * This Web server puts the inbound connection into the pool, A Requestprocessor class instance removes the connection from the pool and processes it */import java.io.*;import java.net.*;p ublic class Jhttp extends Thread{private File Documentrootdirectory;private String indexfilename= "index.html";p rivate serversocket server;private int numThreads = 50;//set the number of server-initiated threads public jhttp (File documentrootdirectory,int port,string indexfilename) throws Ioexception{if (! Documentrootdirectory.isdirectory ()) {throw new IOException (documentrootdirectory+ "does not exist as a directory");} This.documentrootdirectory=documentrootdirectory;this.indexfilename=indexfilename;this.server=new ServerSocket ( Port);} Public Jhttp (File documentrootdirectory,int Port) throws Ioexception{this (Documentrootdirectory,port, "index.html");} Public jhttp (File documentrootdirectory) throws Ioexception{this (documentrootdirectory,80, "index.html");} public void Run () {///opens the thread that handles the request, which pulls a socket connection from the socket pool for data transfer for (int i=0;i<numthreads;i++) {thread T=neW Thread (New Requestprocessor (Documentrootdirectory, Indexfilename)); T.start ();} SYSTEM.OUT.PRINTLN ("Accepting connections on port" +server.getlocalport () + "..."); System.out.println ("Document Root:" +documentrootdirectory);//The server continuously accepts the request while (true) {try {Socket connection= Server.accept (); Requestprocessor.processrequest (connection);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} public static void Main (string[] args) {file docroot;//gets the document root Docroot=new file ("F:\\project");//Set the listener port of the server int port;port= 80;try {jhttp webserver=new jhttp (docroot,port); Webserver.start ();} catch (IOException e) {System.out.println ("Server Could not start because of an "+e.getclass ()); System.out.println (e);}}
Thread class for specific processing connections import Java.util.date;import Java.util.linkedlist;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 LinkedList ();p rivate File documentrootdirectory;private String indexfilename = "index.html" ;p ublic requestprocessor (File documentrootdirectory, String indexfilename) {if (Documentrootdirectory.isfile ()) { throw new IllegalArgumentException ("Documentrootdirectory must be a directory,not a file");} This.documentrootdirectory = documentrootdirectory;//Returns the canonical form of this abstract path name try {this.documentrootdirectory = Documentrootdirectory.getcanonicalfile ();} catch (IOException e) {System.out.println (e);} if (indexfilename! = null) {this.indexfilename = Indexfilename;}} public static void ProcessRequest (socket request) {//will place the socket connection corresponding to each client in the pool, notifying the thread to process their synchronized (pool) {Pool.add ( Pool.size (), request);p Ool.notifyall ();}} @Overridepublic void Run () {//Perform security checks, the requested document cannot exceed the root directory sTring root = Documentrootdirectory.getpath ();//Because of the thread pool policy, threads have to be executed continuously to handle connections 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-g Enerated catch Blocke.printstacktrace ();}} Connection = (Socket) pool.remove (0);} The data exchange of the server client via the socket is a 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 = = ' \ r ' | | c = = ' \ n ') BR Eak;requestline.append ((char) c);} String get = requestline.tostring (); System.out.println (get);//record the first line of the request (to do some decomposition on the line, as below) StringTokenizer st = new StringTokenizer (get); String method = St.nexttoken (); String version = "";//This case currently only handles 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 FIS = new DataInputStream (New Bufferedinputstream (New FileInputStream (thefile))); byte[] Thedata = new byte[(int) thefile.length ()];fis.readfully (thedata); Fis.close (); if (Version.startswith ("HTTP")) {//Send MIME header out.write ("http/1.0 ok\r\n");//The header format specified in the HTTP protocol is to require a carriage return for a newline, it must be \r\ndate now = new Date (); Out.write ("Date:" + Now + "\ r \ n"), Out.write ("server:jhttp/1.0\r\n"), Out.write ("content-length:" + thedata.length+ "\ r \ n"); Out.write (" Content-type: "+ contenttype+" \r\n\r\n ");//Remember to refresh at the end, write buffer remaining data}//send the actual requested file (possibly a picture or other binary file) Raw.write ( Thedata); Raw.flush ();} else {//Cannot find file if (Version.startswith ("HTTP")) {//Send MIME header out.write ("http/1.0 404File not Found on myserver\r\n ");//The header format specified in the HTTP protocol, which requires a carriage return, must be \r\ndate now = new Date () and Out.write (" Date: "+ now +" \ r \ n "); Out.write ("server:jhttp/1.0\r\n"); Out.write ("content-type:text/html\r\n\r\n");} Out.write ("


Java-implemented HTTP simple server

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.