Socket implementation Simple Web server

Source: Internet
Author: User

The previous blog describes how to access a Web server using a socket. There are two key points:

1) familiar with socket programming;

2) be familiar with the HTTP protocol.

The previous article mainly uses sockets to simulate the browser sending (HTTP) requests to (any) Web servers, with a focus on the browser side. This blog, in turn, is about how to use a socket to implement a Web server, how to receive, parse, and process HTTP requests that last reply from the browser.

The HTTP protocol is a communication specification that both the browser and the Web server need to follow, and if we write a program that correctly adheres to the HTTP protocol, the program can theoretically have the functionality of a browser or even a Web server.

Figure 1

As shown in 1, the HTTP protocol is adhered to between the Web server and the browser, whether it is sending data or receiving (parsing) data. It can be quite certain that as long as we are fully familiar with the HTTP protocol structure, whether the implementation of the browser or the implementation of the Web server is only a "simple" socket program development process, in addition, no other mysterious advanced things. and socket program development, a little bit of knowledge of the socket, can write a approximate demo.

In terms of system architecture, systems in the form of web architectures conform to the "producer-consumer" model (essentially, most systems in real life are part of the pattern). The browser continues to generate data (requests), while the Web server continues to process requests for long periods of time.

Figure 2

As shown in 2, the left part of the figure is the "pump" structure in the Web server, the so-called pump, which means it can continue to circulate for a long time. On the right side of the graph, the "From Browser Request" section is "producer", and the producer keeps making requests from the left (Web server) for processing and finally replying to the browser. Note as shown in Figure 2, the Web server handles the data inside the loop body, in other words, before the end of the previous HTTP request processing, the next HTTP request cannot start, that is, each request processing will block the execution of the loop. This serial processing of data is obviously inefficient, in order to solve this problem, we can receive the browser-side HTTP request, not immediately in the current thread processing, but instead of open up a separate thread to process the request (in the. NET can be implemented using asynchronous programming). This way, the request processing does not block the current looping process, see 3

Figure 3

As shown in 3, when a request is received, another thread is opened to process it, and the way in which data is processed in parallel does not affect subsequent request processing.

If you are familiar with socket programming, the above can be easily implemented (exactly as the socket is programmed to do). Now the difficulty is, how does the Web server parse the request data from the browser (string literals) and what format should the browser respond to? The answer is that you must fully understand the HTTP protocol format. As mentioned in the previous blog post, see http://www.cnblogs.com/riky/archive/2007/04/09/705848.html for the HTTP protocol format. We must read the request data sent by the browser and send the reply in the correct format. 4 show Browser request data format:

Figure 4

The red part of the figure is the data transfer method (post or get), the request path (the URL does not contain the host address part), and the HTTP protocol version number. The following text in the "Key: Value" format is a series of data messages that the browser sends to the server (note that these items are optional), and if the browser submits the data by post, the data is immediately below (not shown in the figure). After the Web server reads the request data sent by the browser and finishes processing it, the result must be returned to the browser in the format shown in Figure 5:

Figure 5

As shown in 5, the topmost "key: Value" Format text is some of the data information that the Web server sends to the browser (these items are optional), followed by an HTML document that needs to be sent to the browser (if the page is returned). The browser must read the reply data sent by the Web server and then render (display).

Figure 6

Figure 6 shows a browser-initiated HTTP request that shows the process by which the Web server handles the request. As we can see, the Web server processes only one HTTP request during a single socket connection. Multiple HTTP requests are accompanied by a constant connection and disconnection of the socket.

The article finally uploads a simple Web server written using the socket, enabling the following functions:

1) After running the Web server, you can bind the port to receive HTTP requests from any browser;

2) can display a default home page, such as index.html;

3) Home page provides "login" function, according to post data to the processing page "LOGIN.ZSP" (suffix name can be customized);

4) The Web server to receive the data sent by the browser, the ability to parse (the resolution is very arbitrary) out of the post-pass parameters, and simulate access to the database to check the status, simulation time-consuming wait, and so on;

5) The Web server generates a static page after successful login and replies to the browser. The page displays the login name and the current time.

The entire demo is completely a socket program, only adds the "HTTP protocol" link, the server side whether to receive (parse) data or send data, all need to abide by the HTTP protocol. The final request processing pump code in the Web server is as follows:

1         StaticSocket _socket =NewSockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);//Listening for sockets2         Static voidMain (string[] args)3         {4_socket. Bind (NewIPEndPoint (Ipaddress.any,8081));5_socket. Listen ( -);6_socket. BeginAccept (NewAsyncCallback (OnAccept), _socket);//start receiving HTTP requests from the browser (in fact, the socket connection request)7 Console.read ();8         }9         Static voidonaccept (IAsyncResult ar)Ten         { One             Try A             { -Socket socket = AR. AsyncState asSocket; -Socket new_client = socket. Endaccept (AR);//receive the proxy socket from the browser the                 //The most concurrent processing of HTTP requests -Socket. BeginAccept (NewAsyncCallback (onaccept), socket);//start the next HTTP request receive (when this line of code is placed at No.2, the HTTP request is processed serially, and the previous process blocks the next request processing) -  -                 byte[] Recv_buffer =New byte[1024x768*640]; +                 intREAL_RECV = new_client. Receive (Recv_buffer);//receiving request data from the browser -                 stringRecv_request = Encoding.UTF8.GetString (Recv_buffer,0, REAL_RECV); +Console.WriteLine (recv_request);//to display the request to the interface A  atResolve (recv_request,new_client);//parsing, routing, processing -  -                 //No.2 serial processing of HTTP requests -             } -             Catch -             { in  -             } to}
View Code

Note that in the above code, the No.2 and the Socket.beginaccept () method is placed at the apex, the server side processes the request in parallel, and when placed at No.2, the server serially processes the request. Readers can try each of these ways, and when a request is processed serially, the request processing blocks the processing of subsequent requests (for example, the login takes 10 seconds and others cannot access the site).

Here is the demo:

Figure 7:web After the server is running, the browser accesses the homepage:

Figure 7

Figure 8: First page display in the browser (with login box):

Figure 8

Figure 9: The user clicks the "Login" button, submits the data by post, the Web server resolves, processes, and returns to the new page:

Figure 9

The article is a bit long, partly also distorted (part of the picture was sorted before, did not find a large map, so just look:))

source download: Http://files.cnblogs.com/xiaozhi_5638/socket_webServer.rar

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.