Hypertext Transfer Protocol (HTTP) is an application layer in TCP / IP protocol, which is the most widely known protocol, which is also one of the most core protocols in the interconnect. Similarly, HTTP is also implemented based on C / S or B / S model. In fact, our browser such as Netscape or IE is a client in the HTTP protocol, and some common web server software such as Apache, IIS, and IPlanet Web Server are server-only in the HTTP protocol. The web page is positioned by the server resource, transferred to the browser. After the browser explains, it is seen by the customer.
The WEB's work is based on the client / server computing model, consisting of a web browser (client), and web server (server), and the Hypertext Transfer Protocol (HTTP) is communicated between the two. The HTTP protocol is an application layer protocol between web browsers and web servers, which is a general, stateless, object-oriented protocol.
A complete HTTP protocol session process includes four steps:
◆ Connection, the web browser establishes a connection to the web server, open a virtual file called Socket (socket), and the establishment of this file is successful;
◆ Request, the web browser submits a request to the web server via Socket. HTTP's request is typically a get or post command (POST is used for the transfer of the FORM parameter);
◆ Acknowledges that the web browser submits the request, transferred to the web server via the HTTP protocol. After the web server is connected, transaction processing, the processing result is sent back to the web browser via HTTP, so that the requested page is displayed on the web browser;
◆ Close the connection, the web browser and the web server must be disconnected after the response is completed to ensure that other web browsers can connect with the web server.
Programming ideas
According to the session process of the above HTTP protocol, the method of implementing the web server program of the GET request is implemented, and the method is as follows:
By creating a Serversocket class object, listen to the port (8080) specified by the user, wait and accept the client request to the port. Create the input stream and output stream associated with the socket, and then read the client's request information. If the request type is Get, get the HTML file name accessed from the request information; if the HTML file exists, open the HTML file, transfer the HTTP header information and the HTML file content to the web browser via Socket, then close the file, then close the file, Otherwise send an error message to the web browser. Finally close the socket connected to the corresponding web browser.
Write the source code of the web server httpserver.java file with Java as follows:
//httpserver.java
Import java.net. *;
Import java.io. *;
Import java.util. *;
Import java.lang. *;
Public clas httpserver {
Public static void main (string args []) {
Int port;
Serversocket Server_Socket;
// Read server port number
Try {
Port = integer.parseint (args [0]);
}
Catch (Exception E) {
Port = 8080;
}
Try {
// listen to the server port, wait for the connection request
Server_socket = new serversocket (port);
System.out.println ("Httpserver Running on Port" Server_Socket.getlocalPort ());
// Display startup information
While (true) {
Socket Socket = Server_Socket.accept ();
System.out.println ("New Connection ACCEPTED"
Socket.getinetaddress ()
":" Socket.getPort ());
// Create a division thread
Try {
HttpRequestHandler Request =
New httprequesthandler (socket);
Thread thread = new three (request);
// Start thread
Thread.start ();
}
Catch (Exception E) {
System.out.println (e);
}
}
}
Catch (IOException E) {
System.out.println (e);
}
}
}
Class HttpRequestHandler Implements Runnable
{
Final static string crlf = "/ r / n";
Socket socket;
InputStream INPUT;
OutputStream output;
BUFFEREDReader Br;
// Construction method
Public HttpRequestHandler (Socket Socket) Throws Exception
{
This.socket = Socket;
This.input = Socket.getinputStream ();
this.output = socket.getOutputStream ();
THIS.BR =
New BufferedReader (new input.getinputstream ()));
}
/ / Realize the Run () method of the runnable interface
Public void Run ()
{
Try {
PROCESSREQUEST ();
}
Catch (Exception E) {
System.out.println (e);
}
}
Private Void ProcessRequest () THROWS Exception
{
While (true) {
/ / Read and display the request information submitted by the web browser
String headerline = br.readline ();
System.out.println ("The Client Request IS" HeaderLine);
IF (HeaderLine.equals (CRLF) || HeaderLine.equals (")) Break;
StringTokenizer S = New StringTokenizer (HeaderLine);
String Temp = S.NEXTTOKEN ();
IF (Temp.equals ("Get")) {
String filename = S.NEXTTOKEN ();
Filename = "." filename;
/ / Open the requested file
FileInputStream Fis = NULL;
Boolean FileExists = true;
Try
{
FIS = New FileInputStream (FileName);
}
Catch (FilenotFoundException E)
{
FileExists = false;
}
/ / Complete the response message
String ServerLine = "Server: a Simple Java httpserver";
String statusline = null;
String contenttypeline = null;
String EntityBody = NULL;
String contentthline = "error";
IF (FileExists)
{
StatusLine = "HTTP / 1.0 200 OK" CRLF;
ContentTypeline = "Content-Type:"
ContentType (FileName) CRLF;
ContentLengthline = "Content-Length:"
(New integer (fis.available ())). TOSTRING ()
CRLF;
}
Else
{
Statusline = "http / 1.0 404 not found" CRLF;
ContentTypeline = "text / html";
EntityBody = ""
"
"
"
USAGE: http:// YourHostname: Port /"
"Filename.html body> html>";
}
// Send to server information
Output.write (statusline.getbytes ());
Output.write (ServerLine.getBytes ());
Output.write (ContentTyPeline.getbytes ());
Output.write (ContentLengthline.getBytes ());
Output.write (crlf.getbytes ());
// Send information content
IF (FileExists)
{
SendBytes (Fis, Output);
fis.close ();
}
Else
{
Output.write (EntityBody.getbytes);
}
}
}
// Close the socket and stream
Try {
Output.close ();
br.close ();
Socket.close ();
}
Catch (Exception E) {}
}
Private Static Void Sendbytes (FileInputStream Fis, OutputStream OS)
Throws Exception
{
// Create a 1K buffer
Byte [] buffer = new byte [1024];
INT BYTES = 0;
// output the file to the socket output stream
While ((Bytes = fis.read (buffer))! = -1)
{
Os.write (buffer, 0, bytes);
}
Private static string contenttype (String filename)
{
IF (Filename.endSwith) || filename.endswith (". html")))
{
Return "Text / HTML";
}
Return "filename";
}
}
Programming skills
◆ Main thread design
The main thread is designed to implement the server port listener in the main thread httpserver class, and the server creates a thread instance processing request after accepting a client request. The code is as follows:
Import java.net. *;
Import java.io. *;
Import java.util. *;
Import java.lang. *;
Public clas httpserver {
Public static void main (string args []) {
Port;
Serversocket Server_Socket;
// Read server port number
Try {
Port = integer.parseint (args [0]);
}
Catch (Exception E) {
Port = 8080;
}
Try {
// listen to the server port, wait for the connection request
Server_socket = new serversocket (port);
System.out.println ("Httpserver Running on Port"
Server_Socket.getlocalPort ());
........
........
◆ Connection processing points thread design
The HTTP protocol is implemented in the httpRequestHandler class, which implements the runnable interface, the code is as follows:
Class HttpRequestHandler Implements Runnable
{
Final static string crlf = "/ r / n";
Socket socket;
InputStream INPUT;
OutputStream output;
BUFFEREDReader Br;
// Construction method
Public HttpRequestHandler (Socket Socket) Throws Exception
{
This.socket = Socket;
// Get input and output flow
This.input = Socket.getinputStream ();
this.output = socket.getOutputStream ();
THIS.BR =
New BufferedReader (new input.getinputstream ()));
}
/ / Realize the Run () method of the runnable interface
Public void Run ()
{
Try {
PROCESSREQUEST ();
}
Catch (Exception E) {
System.out.println (e);
}
}
◆ Build a processRequest () method to process information reception and send
As the main content of the RunNable interface, the processRequest () method is called in the run () method to handle the reception of the customer request content and the sender of the server returns information, the code is as follows:
Private Void ProcessRequest () THROWS Exception
{
While (true) {
/ / Read and display the request information submitted by the web browser
String headerline = br.readline (); System.out.println ("The Client Request IS" HeaderLine;
IF (HeaderLine.equals (CRLF) || HeaderLine.equals (")) Break;
/ / Split the customer request according to the space in the request string
StringTokenizer S = New StringTokenizer (HeaderLine);
String Temp = S.NEXTTOKEN ();
IF (Temp.equals ("Get")) {
String filename = S.NEXTTOKEN ();
Filename = "." filename;
...........
...........
After obtaining the client request in the ProcessRequest () method, complete the splitting of the string using a StringTokenizer class, which can achieve a string into a string according to the separator (default space) specified in the string. Function. These strings are sequentially obtained by using the nexttoken () method; the sendbytes () method completes the sending of the information content, and the contentType () method is used to determine the type of file.
Display web page
The INDEX.html file code that displays the web page is as follows:
HEAD>
********* Welcome you! Font> ********* p>
This is a web server that implements Java language p>
Body>
Html>
Running instance
In order to test the correctness of the above program, the compiled httpserver.class, httprequesthandler.class, and the INDEX.html file above the network are placed in the same directory of a host of the network.
First run the server program Java Httpserver 8080, the server program "httpserver running on port 8080" is displayed, and then enters http: // localhost: 8080 / index.html in the browser's address bar, you can display the web page correctly. At the same time, some information will appear in the "HTTPServer Runing On Port 8080" window.