Implementation of a simple Web Server

Source: Internet
Author: User

A simple web server, without considering its performance and robustness, generally only needs to implement functions including server startup. It is used to listen to a port and receive requests from the client, return the response to the client. This article introduces the implementation principle of a simple Web server. It can only process static resource files (text, images, etc.) in a directory ). If Java is used for implementation, the following modules can be included, and the relationship between each module is 1.

Figure 1. Simple Web Server Module

  • Httpserver is the server. It is used to start the server, receive user requests, and return results;
  • Request: Analyze user requests, parse request strings, and obtain the corresponding access URL;
  • Response: generate response results based on user requests and output the results to the client.

The following code shows the implementation process of the server.

Httpserver is the main implementation class of the server. It is used to associate request and response. The source code is as follows:

Package COM. wow. server; import Java. io. file; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; import java.net. inetaddress; import java.net. serversocket; import java.net. socket; import java.net. unknownhostexception;/*** a simple Web Application Server * @ author zhaozheng **/public class httpserver {public static final string web_root = system. getproperty ("user. dir ") + file. separator + "W Ebroot "; Private Static final string shutdown_command ="/shutdown "; private Boolean shutdown = false; public static void main (string [] ARGs) {httpserver Server = new httpserver (); server. start () ;}// start the server and receive user requests to process public void start () {serversocket = NULL; int Port = 8080; try {serversocket = new serversocket (port, 1, inetaddress. getbyname ("127.0.0.1");} catch (unknownhostexception e) {e. Printstacktrace (); system. exit (-1);} catch (ioexception e) {e. printstacktrace (); system. exit (-1);} // if the requested command is not shutdown, the while (! Shutdown) {Socket socket = NULL; inputstream input = NULL; outputstream output = NULL; try {// create a socket for request processing socket = serversocket. accept (); input = socket. getinputstream (); Output = socket. getoutputstream (); // receives the request = new request (input); Request. parser (); // process the request and return the result response = new response (output); response. setrequest (request); response. sendstaticresource (); // close socketsocket. close (); // if the request command is disabled, shutdown the server = request. geturi (). equals (shutdown_command);} catch (ioexception e) {e. printstacktrace (); Continue ;}}}}

This class itself is an application that contains the main method and can be run directly using Java commands. At runtime, it starts a serversocket class to listen to a port of the server. When the command received is not shutdown the server, it creates a socket for receiving requests and returning response results.

The request class is used to receive requests. For the HTTP protocol, there is a certain format for sending requests to the server through a browser. In fact, a request is to receive and analyze the request information, extract the required information, including cookies and URLs. HTTP requests include three parts:

  • Uniform Resource Identifier protocol/version for request methods
  • Request Header
  • Request Entity

There is an empty line between the request header and the request entity. The sample code is as follows:

GET /index.htm HTTP/1.1 Host: www.baidu.com Connection: keep-alive User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: zh-CN,zh;q=0.8 Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3 Cookie: BAIDUID=D275C16E04D9BB2CF55FD9B9654AECAC:FG=1; BDREFER=%7Burl%3A%22http%3A//news.baidu.com/%22%2Cword%3A%22%22%7D;BDUSS=FJ2SzJxSmpKMW1sdVIwMWw3TTBwaHhZRkxFaUdoeG9QLW5GS2dLTUtyZzNhWUpSQVFBQUFBJCQAAAAAAAAAAAouTQytzfcOemhhb3poZW5nNzc1OAAAAAAAAAAAAAAAAAAAAAAAAACAYIArMAAAALCmJHAAAAAA6p5DAAAAAAAxMC4zNi4xNDcblVA3G5VQd; BDUT=5b2fD275C16E04D9BB2CF55FD9B9654AECAC138a495329b1; MCITY=-%3A; shifen[3113720932]=1357565900; H_PS_PSSID=1445_1661

The request class is used to receive byte streams sent from socket sockets and parse them according to the HTTP request format. For a simple web server, we only need to parse its Uri, so that the corresponding resources can be found through file matching. The specific implementation code is as follows:

Package COM. wow. server; import Java. io. ioexception; import Java. io. inputstream;/*** the specific format of the received request string is as follows: * Get/aaa.htm HTTP/1.1 * Host: 127.0.0.1: 8080 * connection: keep-alive * User-Agent: mozilla/5.0 (Windows NT 6.1) applewebkit/537.11 (khtml, like gecko) Chrome/23.0.20.1.97 Safari/537.11 * accept: text/html, application/XHTML + XML, application/XML; Q = 0.9, q = 0.8 * accept-encoding: gzip, deflate, SDCh * accept -Language: ZH-CN, ZH; q = 0.8 * accept-charset: GBK, UTF-8; q = 0.7 ,*; Q = 0.3 ** @ author zhaozheng **/public class request {private inputstream input; private string URI; public request (inputstream input) {This. input = input;} public void Parser () {stringbuffer request = new stringbuffer (); byte [] buffer = new byte [2048]; int I = 0; try {I = input. read (buffer);} catch (ioexception e) {e. printstacktrace (); I =-1 ;} For (int K = 0; k <I; k ++) {request. append (char) buffer [k]);} uri = parseruri (request. tostring ();} private string parseruri (string requestdata) {int index1, index2; index1 = requestdata. indexof (''); If (index1! =-1) {index2 = requestdata. indexof ('', index1 + 1); If (index2> index1) {return requestdata. substring (index1 + 1, index2) ;}} return NULL ;}public string geturi () {return URI ;}}

The code above shows that the parser method is used to parse a specific request. It receives the byte stream of the socket, processes it, and obtains the URI information.

After obtaining the URI information, you can map the URI to an application or directory on the server. This article only implements a simple static resource server, which maps the URI to a file in a directory. If the file exists, it opens and reads the file information. If the file does not exist, an error message is returned directly. The response class is used to process the logic. At the same time, it writes the file stream back to the Socket socket, and the Socket socket returns the response result to the client.

For the HTTP protocol, the response also has certain format requirements and cannot send information in any format. Otherwise, the browser cannot receive and process the information. HTTP response results also include three parts:

  • Protocol Status Code Description
  • Response Header
  • Response entity segment

There is also an empty line between the response header and the response object segment. The specific example is as follows:

HTTP/1.1 200 OK Date: Mon, 07 Jan 2013 14:31:36 GMT Server: BWS/1.0 Content-Length: 4029 Content-Type: text/html;charset=gbkCache-Control: private Expires: Mon, 07 Jan 2013 14:31:36 GMT Content-Encoding: gzip Set-Cookie: H_PS_PSSID=1445_1661; path=/; domain=.baidu.comConnection: Keep-Alive

When the requested file does not exist in the response class, a fixed response text must be sent to the client. The format of the Response document must be organized in strict accordance with the HTTP Response format; otherwise, the client cannot receive the request. The specific implementation source code is as follows:

Package COM. wow. server; import Java. io. file; import Java. io. fileinputstream; import Java. io. ioexception; import Java. io. outputstream;/*** response result ** @ author zhaozheng **/public class response {private outputstream output; private request; Private Static final int buffer_size = 1024; public Response (outputstream output) {This. output = output;} public void setrequest (request) {This. request = Request;} // send a static resource to the client. If the local server has a corresponding file, return; otherwise, return public void sendstaticresource () on the 404 page () {byte [] buffer = new byte [buffer_size]; int ch; fileinputstream FD = NULL; try {file = new file (httpserver. web_root, request. geturi (); If (file. exists () {fiis = new fileinputstream (File); CH = fiis. read (buffer); While (Ch! =-1) {output. write (buffer, 0, CH); CH = FCM. read (buffer, 0, buffer_size) ;}} else {string errormessage = "HTTP/1.1 404 file not found \ r \ n" + "Content-Type: text/html \ r \ n "+" Content-Length: 24 \ r \ n "+" \ r \ n "+" 

Analyze the response class. In the sendstaticresource method, find the corresponding file in the directory based on the requested URI. If yes, read the file directly and return it; otherwise, an error message is returned to the client.

Of course, if you want to run the program, you still need to create a webrootdirectory under the project directory, where you can save an aaa.htm file.

1. Start the Java application and use netstat to check that the program occupies port 8080.

2. Access the URL through a browser: http: // 127.0.0.1: 8080/aaa.htm.

32.16if index1.htm does not exist, the system returns the 404 file not found information.

4. You can directly enter http: // 127.0.0.1: 8080/shutdown to shut down the server.
So far, a simple web server has been implemented, and its functions are incomplete. However, it is helpful for beginners to understand the processing, response, and general workflow of the 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.