Introduction to HTTP protocol
Hypertext Transfer Protocol (HTTP) is located in the TCP/IP protocol application layer, is the most well-known protocol, but also one of the most core protocols in the interconnection network, the same, HTTP is based on C/s or B + + model implementation. In fact, the browsers we use, such as Netscape or IE, are the clients that implement the HTTP protocol, and some common Web server software such as Apache, IIS, and iplanet Web servers are the servers in the HTTP protocol. Web pages are positioned by server resources and transmitted to browsers, which are interpreted by the browser and are seen by customers.
The work of the Web is based on the client/server computing model, consisting of a Web browser (client) and a Web server (server), which communicates with a Hypertext Transfer Protocol (HTTP). The HTTP protocol is an application layer protocol between Web browsers and Web servers, and is a universal, stateless, object-oriented protocol.
A complete HTTP protocol session process consists of four steps:
Connection, the Web browser establishes a connection to the Web server, and opens a virtual file called a socket (socket), which marks the successful connection establishment;
Request, the Web browser submits the request to the Web server via the socket. HTTP requests are typically a GET or post command (post is used for a form parameter pass);
Answer, the Web browser submits the request and passes it through the HTTP protocol to the Web server. When the Web server receives the transaction, the processing results are returned to the Web browser via HTTP, thus displaying the requested page in the Web browser;
Close the connection and the Web browser must disconnect from the Web server to ensure that other Web browsers can connect to the Web server after the answer is complete.
Programming Ideas
Based on the session process of the HTTP protocol above, the method for implementing the Web server program for GET requests in this example is as follows:
By creating the ServerSocket class object, listens for the user-specified port (8080), waits for and accepts the client request to the port. Creates an input stream and an output stream associated with the socket, and then reads the client's request information. If the request type is get, the access HTML file name is obtained from the request information, and if the HTML file exists, the HTML file is opened, the HTTP header information and the contents of the HTML file are passed back to the Web browser via the socket, and the file is closed, otherwise the error message is sent to the Web browser Finally, close the socket that is connected to the appropriate Web browser.