Socket implements simple Web server and socketweb Server

Source: Internet
Author: User

Socket implements simple Web server and socketweb Server

The previous blog introduced how to use socket to access the web server. There are two key points:

1) familiar with Socket programming;

2) be familiar with HTTP.

In the previous article, we used socket to simulate a browser to send (HTTP) requests to (any) Web servers, focusing on the browser side. This blog explains in turn how to use socket to implement Web servers, and how to receive, analyze, and process HTTP requests from browsers.

HTTP protocol is a communication standard that browsers and Web servers must comply with. If we write a program that correctly complies with the HTTP protocol, theoretically, this program can be used by browsers or even Web servers.

Figure 1

As shown in figure 1, both the sending and receiving (parsing) data between the Web server and the browser comply with the HTTP protocol. As long as we are fully familiar with the HTTP protocol structure, the implementation of browsers and Web servers is only a "simple" Socket program development process, there are no other mysterious and profound things. Socket program development, a little bit of socket-related knowledge, can write a rough demo.

In terms of system architecture, all systems in the form of Web architecture comply with the "producer-consumer" Model (in essence, most systems in real life belong to this model ). The browser continuously generates data (requests), while the Web server continuously processes requests for a long time.

Figure 2

As shown in figure 2, the left part of the figure is the "pump" structure in the Web server. The so-called pump means that it can continue to operate cyclically for a long time. The "from browser request" section on the right is displayed as "producer". The producer continuously sends requests, and the left side (Web Server) continuously processes the requests and finally replies to the browser. Note: As shown in figure 2, the data processed in the Web server is inside the loop body. In other words, the last HTTP request cannot start before the processing of the previous HTTP request ends, that is, every request processing will block the execution of the loop. This method of serial data processing is obviously inefficient. To solve this problem, we can not process the HTTP request in the current thread immediately after receiving the HTTP request from the browser, instead, open up independent threads to process requests (in.. NET ). In this way, request processing does not block the current loop process, as shown in figure 3.

Figure 3

As shown in figure 3, after receiving the request, other threads are opened for processing. This method of parallel data processing does not affect subsequent request processing.

If you are familiar with Socket programming, the above mentioned can be easily implemented (based on Socket programming ). How does the Web server parse the request data from the browser (a string of text) and reply to the browser in what format? The answer is that you must fully understand the HTTP protocol format. As mentioned in the previous blog, for the HTTP protocol format, see http://www.cnblogs.com/riky/archive/2007/04/09/705848.html. We must read the request data sent by the browser and send a reply in the correct format. 4. display the format of browser request data:

Figure 4

In the figure, the red part is the data transmission method (post or get), Request Path (the url does not include the host address part), and HTTP Protocol version number. The following text in the "Key: Value" format is a series of data information sent to the server by the browser (note that these items are optional). If the browser submits data in post mode, the data is immediately followed (not shown in the figure ). After the Web server reads and processes the request data sent by the browser, it must return the result to the browser in Figure 5:

Figure 5

As shown in figure 5, the top text in the "Key: Value" format is some data information that the Web server sends to the browser (these items are optional), followed, the following is the HTML document 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) it ).

Figure 6

Figure 6 shows an HTTP request initiated by the browser and the process of processing the request by the Web server. We can see that the Web server only processes one HTTP request during a Socket connection. Multiple HTTP requests are constantly connected and disconnected with the Socket.

The last part of the article uploads a simple Web server written using Socket, which can implement the following functions:

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

2 bytes can display a batch of first pages, such as index.html;

3) The homepage provides the "login" function, which transfers data to the "login. zsp" (the suffix can be customized) on the "Post" page );

4) The Web server receives the data sent by the browser, parses (the resolution method is very casual) the parameters passed by the post, and simulates the database access to check the logon status and simulate the time-consuming wait;

5) The Web server generates a static page after successful logon and returns it to the browser. The Logon Name and current time are displayed.

The entire demo is a Socket program. It only adds the "HTTP protocol" link. The server must comply with the HTTP protocol for receiving (parsing) data or sending data. The final request processing pump code in the Web server is as follows:

1 static Socket _ socket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // listen to socket 2 static void Main (string [] args) 3 {4 _ socket. bind (new IPEndPoint (IPAddress. any, 8081); 5 _ socket. listen (100); 6 _ socket. beginAccept (new AsyncCallback (OnAccept), _ socket); // start to receive http requests from the browser (actually socket connection requests) 7 Console. read (); 8} 9 static void OnAccept (IAsyncResult ar) 10 {11 try12 {13 Socket socket = ar. asyncState as Socket; 14 Socket new_client = socket. endAccept (ar); // receives the proxy socket15 from the browser // NO.1 processes the http request 16 socket in parallel. beginAccept (new AsyncCallback (OnAccept), socket); // starts receiving the next http Request (when this line of code is placed at No. 2, it is to process http requests in a serial manner, the previous processing process blocks the next request processing.) 17 18 byte [] recv_buffer = new byte [1024*640]; 19 int real_recv = new_client.Receive (recv_buffer ); // receives the browser's request data 20 string recv_request = Encoding. UTF8.GetString (recv_buffer, 0, real_recv); 21 Console. writeLine (recv_request); // display the request to interface 22 23 Resolve (recv_request, new_client ); // resolution, routing, processing 24 25 // No. 2 serial processing http request 26} 27 catch28 {29 30} 31}View Code

Note that when the socket. BeginAccept () method is placed at No. 1 in the above Code, the server will process the request in parallel, and when it is placed at No. 2, the server will process the request in series. You can try each method. When processing requests in serial mode, the request processing process will block the processing of subsequent requests (for example, it takes 10 seconds to log on, and others will not be able to access the website ).

The following is a demo:

Figure 7: After the Web server is running, the browser accesses the Home Page:

Figure 7

Figure 8: display on the browser's homepage (including the logon box ):

Figure 8

Figure 9: the user clicks the "login" button to submit data in Post mode. The Web server parses and processes the data and returns to the new page:

Figure 9

The article is a bit long, and some of it is still distorted (some of the pictures have been sorted out before, but the big picture is not found, so let's take a look at it :))

Source code download: http://files.cnblogs.com/xiaozhi_5638/socket_webServer.rar


The simplest multi-thread Web server implemented by java Socket programming

Import java. io. PrintWriter;
Import java.net. ServerSocket;
Import java.net. Socket;

Public class Test {
Public static void main (String [] args) throws Exception {
ServerSocket server = new ServerSocket (888 );
While (true ){
Socket s = server. accept ();
Processer p = new Processer (s );
Thread t = new Thread (p );
T. start ();
}
}
}

Class Processer implements Runnable {
Private Socket socket;

Public Processer (Socket s ){
// TODO Auto-generated constructor stub
This. socket = s;
}
@ Override
Public void run (){
Try {
PrintWriter out = new PrintWriter (socket. getOutputStream (), true );
Out. println ("HTTP/1.0 200 OK ");
Out. println ("Content-Type: text/html; charset = UTF-8 ");
Out. println ();
Out. println ("Out. close ();
} Catch (Exception ex ){
Ex. printStackTrace ();
} Finally {
Try {
Socket. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}

}
}

Java Project (not web) how to obtain the request, response, some simple web servers implemented using socket on the Internet, the client sends

Responding to http requests and returning static web pages are more similar to traditional web servers, and the main tasks of tomcat are still different.

The client should be a browser. When the browser reads the img tag, it will view the image address and then send a request to obtain the image. If your current simple server only supports html pages, but does not return jpg and other image files, you naturally cannot display images in your browser.
 

Related Article

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.