Java implementation of a simple Web server

Source: Internet
Author: User

A Web server, also known as a Hypertext Transfer Protocol server, communicates with its clients using HTTP, and the Java-based Web server uses two important classes.

The Java.net.Socket class and the Java.net.ServerSocket class, and communicates based on sending HTTP messages.

This simple Web server will have the following three classes:

*httpserver

*request

*response

Application entry in the Httpserver class, the main () method creates a Httpserver instance, and then calls its await () method, as the name implies, the await () method on the specified port

Waits for an HTTP request, processes it, sends a response back to the client, and waits until the shutdown command is received.

The application sends only requests for static resources at the specified directory, such as HTML files and images, and it can also display incoming HTTP request byte streams to the console, but it does not send

Any header information to the browser, such as date or cookies.

The following are the source code for these classes:

Request:

Package Cn.com.server;import Java.io.inputstream;public class Request {private InputStream input;private String URI; Public Request (InputStream input) {this.input=input;} public void Parse () {//read A set of characters from the Socketstringbuffer request=new StringBuffer (2048); int i;byte[] Buf Fer=new byte[2048];try {i=input.read (buffer);} catch (Exception e) {e.printstacktrace (); i=-1;} for (int j=0;j<i;j++) {request.append ((char) buffer[j]);} System.out.print (Request.tostring ()); Uri=parseuri (request.tostring ());} public string Parseuri (string requeststring) {int index1,index2;index1=requeststring.indexof (""); if (index1!=-1) { Index2=requeststring.indexof ("", index1+1); if (index2>index1) {return requeststring.substring (INDEX1+1,INDEX2);}} return null;} Public String GetURI () {return this.uri;}}
The request class represents an HTTP request that can be passed the InputStream object to create the request object, and you can call the Read () method in the InputStream object to read the HTTP request

The original data.

The parse () method in the source code above is used to parse the original data of the HTTP request, and the parse () method calls the Private method Parseuri () to parse the URI of the HTTP request, except that there is no

Doing too much work, the Parseuri () method stores the URI in the variable URI, and calling public method GetURI () returns the requested URI.

Response:

<span style= "font-size:10px;" >package cn.com.server;import java.io.file;import Java.io.fileinputstream;import java.io.IOException;import java.io.outputstream;/** * HTTP Response = status-line * * ((General-header | response-header | entity-header) CRLF) * C RLF * [message-body] * status-line=http-version sp status-code sp reason-phrase CRLF * */public class Response {private St atic final int buffer_size=1024; Request request;outputstream output;public Response (outputstream output) {this.output=output;} public void Setrequest (Request request) {This.request=request;} public void Sendstaticresource () throws ioexception{byte[] Bytes=new byte[buffer_size]; FileInputStream fis=null;try {file File=new file (Httpserver.web_root,request.geturi ()); if (File.exists ()) {Fis=new FileInputStream (file), int ch=fis.read (bytes,0,buffer_size), while (Ch!=-1) {output.write (bytes, 0, buffer_size); ch= Fis.read (bytes, 0, buffer_size);}} Else{//file not foundstring errormessage= "http/1.1 404 File Not found\r\n" + "Content-type:text/html\r\n "+" content-length:23\r\n "+" \ r \ n "+" The response object is created in the await () method of the Httpserver class by passing in the OutputStream obtained in the socket. 

The response class has two public methods: Setrequest () and Sendstaticresource (), and the Setrequest () method receives a Request object as a parameter, Sendstaticresource ()

method is used to send a static resource to a browser, such as an HTML file.

Httpserver:

Package Cn.com.server;import Java.io.file;import Java.io.inputstream;import java.io.outputstream;import Java.net.inetaddress;import Java.net.serversocket;import Java.net.socket;public class HttpServer {/** * WEB_ROOT is the directory where our HTML and other files reside. * Package,web_root is the "Webroot" directory under the * working directory. * The working directory is the location of the file system * from where the Java command was invoke. */public static final String web_root=system.getproperty ("User.dir") +file.separator+ "Webroot";p rivate static final String shutdown_command= "/shutdown";p rivate boolean shutdown=false;public static void Main (string[] args) {Httpserver Server=new httpserver (); server.await ();} public void await () {ServerSocket serversocket=null;int port=8080;try {serversocket=new serversocket (port,1, Inetaddress.getbyname ("127.0.0.1"));} catch (Exception e) {e.printstacktrace (); System.exit (0);} while (!shutdown) {Socket Socket=null;inputstream input=null;outputStream output=null;try {socket=serversocket.accept (); Input=socket.getinputstream (); Output=socket.getoutputstream ();//create request object and Parserequest request=new request (input); Request.parse ();//create Response Objectresponse response=new response (output); Response.setrequest (request); Response.sendstaticresource ();} catch (Exception e) {e.printstacktrace (); continue;}}}
This class represents a Web server that can handle requests for static resources for a specified directory, including directories and all subdirectories specified by the public static variable final web_root.

Now create an HTML page in Webroot, named Index.html, the source code is as follows:

<! DOCTYPE html>

Now start the Web server and request a index.html static page.

The output of the corresponding console:


So, a simple HTTP server is done.

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