Java implementation of simple HTTP server

Source: Internet
Author: User

The Web server's interaction with the user is not supported in the initial phase of the Web. That is, the Web server cannot dynamically generate the pages that the user wants to access, and the pages provided to the user by the Web server are generated in advance. So it is also said that this page is a static page.
For example, if a user requests access to http://localhost:8088/hello1.htm, the Web server obtains hello1.htm (already exists) from its desired directory. It is then returned to the user via the HTTP protocol.

Let's simulate this process. Because the HTTP protocol is an application-layer protocol, TCP-based, we use a Java socket to write an HTTP server.

Writing Httpserver
Importjava.io.*;Importjava.net.*; Public  class httpserver {    Private Static Final intPort =8088;PrivateServerSocket ServerSocket =NULL; Public Httpserver()throwsIOException {ServerSocket =NewServerSocket (port); System.out.println ("Httpserver startup ok ..."); } PublicStringgetrequest(Socket socket)throwsIOException {InputStream socketin = Socket.getinputstream ();intSize = Socketin.available ();byte[] Requestbuff =New byte[Size]; Socketin.read (Requestbuff);return NewString (Requestbuff); } PublicStringGetURI(String request) {String Firstline = request.substring (0, Request.indexof ("\ r \ n")); string[] Parts = Firstline.split (" ");returnparts[1]; } PublicStringgetContentType(String URI) {/ * Determines the type of HTTP response body * /String ContentType;if(Uri.indexof ("HTML") != -1|| Uri.indexof ("htm") != -1) ContentType ="Text/html";Else if(Uri.indexof ("JPG") != -1|| Uri.indexof ("JPEG") != -1) ContentType ="Image/jpeg";Else if(Uri.indexof ("GIF") != -1) ContentType ="Image/gif";ElseContentType ="Application/octet-stream";returnContentType; } PublicInputStreamgetresponsecontent(String URI)throwsFileNotFoundException {InputStream Htmlinputstream =NewFileInputStream (System.getproperty ("User.dir") +"/webroot"+ URI);returnHtmlinputstream; } PublicStringAssembleresponsehead(String URI, String contentType) {/ * Create HTTP response results * /        the first line of the//HTTP responseString Responsefirstline ="http/1.1 ok\r\n";//HTTP response headerString Responseheader ="Content-type:"+ ContentType +"\r\n\r\n";returnResponsefirstline + Responseheader; } Public void Service()throwsinterruptedexception { while(true) {socket socket;Try{socket = serversocket.accept ();                String request = getrequest (socket); System.out.println ("Httpserver receive request:\n"+ request);                String URI = GetURI (request);                String ContentType = getContentType (URI);                OutputStream out = Socket.getoutputstream (); Out.write (Assembleresponsehead (URI, ContentType). GetBytes ());intLen =0;byte[] buffer =New byte[ -]; InputStream Htmlinputstream = getresponsecontent (URI); while(len = htmlinputstream.read (buffer))! =-1) Out.write (buffer,0, Len); Thread.Sleep ( +); Socket.close ();//Close TCP connection}Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }        }    } Public Static void Main(string[] args)throwsIOException, interruptedexception {httpserver httpserver =NewHttpserver ();//System.out.println (System.getproperty ("User.dir"));Httpserver.service (); }}
Create hello1.htm

Then place a hello1.htm page under the project's directory/webroot:

Hello1.htm is simple, show title HelloWorld

<html><head><title>HelloWorld</title></head><body >  <h1>Hello</h1></body></html>
Visit hello1.htm

Start Httpserver, Access http://localhost:8088/hello1.htm in the browser, see the console output of Eclipse

get / hello1.htm  http/1.1  host : localhost : 8088  connection : keep-alive  cache-control : max-age=0  accept : text/html,application/xhtml+xml, application/xml;q=0.9,image/webp,*/*;q=0.8  user-agent : mozilla/5.0 (X11; Linux x86_64) applewebkit/537.36 (khtml, like Gecko) chrome/43.0.2357.125 safari/537.36  accept-encoding : gzip, deflate, SDCH  accept-language : zh-cn,zh;q=0.8,en-us;q=0.6,en;q= 0.4   

This is the HTTP message requested by the browser, including the HTTP header, the request method, and sometimes the request body (not here).
The browser appears as:


If this simple httpsever is finished, I will continue to study the HTTP server that simulates the servlet.

Java implementation of simple HTTP 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.