Write http server by yourself --- java

Source: Internet
Author: User

The simplest http server, downloadable source code: http://download.csdn.net/detail/ajaxhu/6356885


Let's take a rough look at the principles. A browser can open a webpage in three phases:

1. Send a request string (including the URL entered by the user) in a certain format to the server through socket, for example:

Accepttext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Encodinggzip, deflateAccept-Languagezh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3Connectionkeep-aliveHostlocalhost:8001User-AgentMozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0

2. The server receives the request string from the browser and parses the requested URL. The URL actually corresponds to the file on the server. For example, http: \ www.demo.com actually corresponds to http: \ www.demo.com \ index.html on the server. The server reads the file index.html into the byte array and adds header information (also a string ), return to the browser that sends the request.
3. the browser receives the byte stream returned by the server. Based on the returned header information, it determines the original data type of the returned byte array (webpage, image, and others). For example, the returned header information is as follows:
Content-Type text/html
The returned byte array is originally an html page. The browser parses the html page and displays the data. If the server returns the following header information:
Content-Type image/jpeg
The returned byte array is an image, and the browser stores the byte array as an image to display the image.
The source code is given below: Note: 1. to run a program, you need to create a webapp folder in the same directory and put the website you want to run into (currently only html, jpg, gif, and png are supported) 2. program running parameters: You can run the program without parameters. Port 80 is bound by default, which may conflict. You can add a parameter to set the port. For example, java-jar MyHtmlServer. jar 80018001 is the bound port number. 3. After running the program, enter http: // localhost: Port Number/resource path in the browser. For example, if the 8001 port is bound, an index.html file is placed under the webappfile. to access this file, enter http: // localhost:/index.html in the browser. If port 80 is bound, enter http: // localhost/index.html. the browser uses port 80 as the server port by default. Source code:
Import java. io. bufferedReader; import java. io. byteArrayOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. interruptedIOException; import java. io. outputStream; import java.net. serverSocket; import java.net. socket; public class MyHtmlServer {public static void main (String [] args) throws IOExc Eption {int port = 80; if (args. length> 0) port = Integer. valueOf (args [0]); new MyHtmlServer (). start (port);}/*** start the http server on the specified port * @ param port the specified port * @ throws IOException */public void start (int port) throws IOException {ServerSocket server = new ServerSocket (port); System. out. println ("server start at" + port + "........... "); while (true) {Socket client = server. accept (); ServerThread serverthread = new ServerT Hread (client); serverthread. start () ;}}/*** Server Response Thread. Every time a browser request is received, a ServerThread Thread * @ author **/class ServerThread extends Thread {Socket client is started; public ServerThread (Socket client) {this. client = client;}/*** reads the file content and converts it to a byte array * @ param filename file name * @ return * @ throws IOException */public byte [] getFileByte (String filename) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream (); File file = new File (filename); FileInputStream FCM = new FileInputStream (file); byte [] B = new byte [1000]; int read; while (read = FCM. read (B ))! =-1) {baos. write (B, 0, read. close (); baos. close (); return baos. toByteArray ();}/*** analyze the url in the http request, analyze the resource requested by the user, and normalize the request url * For example, request "/" to "/index.html ", "/index" must be normalized to "/index.html" * @ param queryurl: User's original url * @ return: normalized url, that is, the path */private String getQueryResource (String queryurl) {String queryresource = null; int index = queryurl. indexOf ('? '); If (index! =-1) {queryresource = queryurl. substring (0, queryurl. indexOf ('? ');} Elsequeryresource = queryurl; index = queryresource. lastIndexOf ("/"); if (index + 1 = queryresource. length () {queryresource = queryresource + "index.html";} else {String filename = queryresource. substring (index + 1); if (! Filename. contains (". ") queryresource = queryresource + ". html ";} return queryresource;}/*** sets the http Response Header Based on the Resource Type requested by the user, mainly to determine the file type requested by the user (html, jpg ...) * @ param queryresource * @ return */private String getHead (String queryresource) {String filename = ""; int index = queryresource. lastIndexOf ("/"); filename = queryresource. substring (index + 1); String [] filetypes = filename. split ("\\. "); String filetype = filetypes [filetypes. l Ength-1]; if (filetype. equals ("html") {return "HTTP/1.0200OK \ n" + "Content-Type: text/html \ n" + "Server: myserver \ n "+" \ n ";} else if (filetype. equals ("jpg") | filetype. equals ("gif") | filetype. equals ("png") {return "HTTP/1.0200OK \ n" + "Content-Type: image/jpeg \ n" + "Server: myserver \ n "+" \ n ";} else return null;} @ Overridepublic void run () {InputStream is; try {is = client. getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (is); int readint; char c; byte [] buf = new byte [1000]; OutputStream OS = client. getOutputStream (); client. setSoTimeout (50); byte [] data = null; String cmd = ""; String queryurl = ""; int state = 0; String queryresource; String head; while (true) {readint = is. read (); c = (char) readint; boolean space = Character. isWhitespace (readint); switch (state) {case 0: if (space) continue; State = 1; case 1: if (space) {state = 2; continue;} cmd + = c; continue; case 2: if (space) continue; state = 3; case 3: if (space) break; queryurl + = c; continue;} break;} queryresource = getQueryResource (queryurl); head = getHead (queryresource); while (true) {try {if (readint = is. read (buf)> 0) {// System. out. write (buf);} else if (readint <0) break;} catch (InterruptedIOException e) {data = getFileByte ("webapp" + queryresourc E);} if (data! = Null) {OS. write (head. getBytes ("UTF-8"); OS. write (data); OS. close (); break ;}}catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}}



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.