By Budi kurniawan translated by javafuns
04/23/2003
Edit annotation:This article is adapted from BudiPublished by myself about TomcatBooks on internal implementation principles.You can find more information on his website.
WebThe server is also called the Hypertext Transfer Protocol (HTTP) server because it uses the HTTP protocol to communicate with the client. It usually refers to Web browsers. Java-based Web servers use two important classes,java.net.Socket
Andjava.net.ServerSocket
Therefore, this article first discusses the HTTP protocol and the two classes. Then, I will explain a simple web server program included in this book.
The Hypertext Transfer Protocol (HTTP)
HTTP enables the WebServersAnd the browser sends and receives data over the Internet. it is a request-response protocol-when a client initiates a request, the server responds to the request. HTTP uses a trusted TCP connection. By default, port 80 of TCP is used. the first version of HTTP is HTTP/0.9, followed by HTTP/1.0. the current version is HTTP/1.1 defined by RFC 2616(scheme.
This section briefly introduces HTTP 1.1, which helps you understand the messages sent by web server applications. If you are interested in more details, read RFC 2616.
When using HTTP, the Client Always starts a transaction by establishing a connection, and then sends an HTTP request. the server does not actively contact the client or establish a callback to connect to the client (is in no position to contact a client or to make a callback connection to the client ). both the client and server can abort a connection in advance. for example, when using a Web browser, you can click the stop button on the browser to end the file download process, effectively closing the HTTP connection with the Web server.
HTTP requests
An HTTP request consists of three parts:
An example of an HTTP request is as follows:
POST /servlet/default.jsp HTTP/1.1
Accept: text/plain; text/html
Accept-Language: en-gb
Connection: Keep-Alive
Host: localhost
Referer: http://localhost/ch8/SendDetails.htm
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
Content-Length: 33
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
LastName=Franks&FirstName=Michael
Method-Uri-Protocol/version appears in the 1st rows of the request.
POST /servlet/default.jsp HTTP/1.1
POST
Is the request method,/servlet/default.jsp
Uri,HTTP/1.1
Is the value of Protocol/version.
Each HTTP request can use any of the following methods:GET
,POST
,HEAD
,OPTIONS
,PUT
,DELETE
, AndTRACE
.GET
AndPOST
Is the two most common requests in Internet programs.
Uri completely specifies an Internet resource. Uri is usually parsed relative to the root directory of the server. Therefore, it should always/
Start
. Url is actually a type of Uri. The Protocol version indicates the version number of the HTTP protocol in use.
The request header contains useful information about the client environment and request body, such as the browser language settings and length of the Request body. Each request header is separated by the CRLF sequence.
There is a very important blank line (CRLF sequence) between the header and the subject ). this line marks the beginning of the Request body. some Internet programming books hold that this CRLF is part of 4th HTTP requests.
In the previous HTTP request, the request subject is simply one line as follows:
LastName=Franks&FirstName=Michael
In a typical HTTP request, the request subject can be longer than this.
HTTP responses
Similar to a request, an HTTP response is composed of three parts:
The following is an example of an HTTP response:
HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Date: Mon, 3 Jan 1998 13:13:33 GMT
Content-Type: text/html
Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT
Content-Length: 112
<title>HTTP Response Example</title>Welcome to Brainy Software
</body>
The first line of the response header is similar to the first line of the request header. the first line tells you that the protocol used is HTTP Version 1.1. The request is successful (200 = success) and everything is correct.
Similar to the request header, the Response Header also contains useful information. The response body is HTML content. The header and body are also separated by the crlfs sequence.
The socket class
A socket is an endpoint of a network connection. the socket allows the program to read data from the network and send data to the network. two programs on two different machines can communicate by sending and receiving byte streams at one connection. to send a message to another program, you must know its IP address and its socket port.JavaSocket usage injava.net.Socket
Class.
To create a socket, you can useSocket
One of the constructors of the class accepts the host name and port number:
public Socket(String host, int port)
host
Is the remote machine name or IP address,port
Is the port number of the remote program. For example, to connect port 80 of Yahoo.com, you should build the socket as follows:
new Socket("yahoo.com", 80);
Once you have successfully createdSocket
Class, you can use it to send and receive byte streams. When sending byte streams, you must first callSocket
ClassgetOutputStream
Method acquisitionjava.io.OutputStream
Object. When sending text to a remote programOutputStream
Constructjava.io.PrintWriter
Object. To receive byte streams from the other end, you must callSocket
ClassgetInputStream
Method to obtainjava.io.InputStream
Object
.
The following code snippet establishes a socket to communicate with the local HTTP server (127.0.0.1 means a local host), sends an HTTP request, and receives a response from the server. It createsStringBuffer
The object contains the response content and then prints it to the console.
Socket socket = new Socket("127.0.0.1", "8080");
OutputStream os = socket.getOutputStream();
boolean autoflush = true;
PrintWriter out = new PrintWriter( socket.getOutputStream(), autoflush );
BufferedReader in = new BufferedReader(
new InputStreamReader( socket.getInputStream() ));
// send an HTTP request to the web server
out.println("GET /index.jsp HTTP/1.1");
out.println("Host: localhost:8080");
out.println("Connection: Close");
out.println();
// read the response
boolean loop = true;
StringBuffer sb = new StringBuffer(8096);
while (loop) {
if ( in.ready() ) {
int i=0;
while (i!=-1) {
i = in.read();
sb.append((char) i);
}
loop = false;
}
Thread.currentThread().sleep(50);
}
// display the response to the out console
System.out.println(sb.toString());
socket.close();
To get the correct response from the Web server, you must send an HTTP request following the HTTP protocol. if you have read the previous section "The Hypertext Transfer Protocol (HTTP)", you will understand the HTTP requests in the code above.
The
ServerSocket
Class
Socket
Class represents a "client" ("client") socket, which is the socket built when you want to connect to a remote server program. if you want to implement a server program, such as HTTP server or FTP server, you need a different method. this is because your server must be persistent and ready to receive requests at any time, because it does not know when a client program will connect to it.
For this reason, you must usejava.net.ServerSocket
Class. This is an implementation of the server socket. The server socket waits for the connection request from the client. Every time it accepts the connection request, it createsSocket
Instance location and client communication.
To create a server socket, you must useServerSocket
One of the four constructors provided by the class. you need to specify the IP address and the port number of the server socket listener. generally, the IP address is 127.0.0.1, which means that the server socket will listen on the local machine. the IP address of the server socket is also called the binding address. another important attribute of the server socket is its backlog, which refers to the maximum length of the Connection Request queue that can be tolerated before the server socket begins to reject new requests.
ServerSocket
One of the constructors of the class has the following method declaration:
public ServerSocket(int port, int backLog, InetAddress bindingAddress);
For this constructor, the binding address must bejava.net.InetAddress
An instance
. A simple constructionInetAddress
The object is called through its static method.getByName
, Pass a string containing the host name to it:
InetAddress.getByName("127.0.0.1");
The following line of code constructsServerSocket,
Listen to
Port 8080, and the backlog value is set to 1.
new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));
Once you haveServerSocket
Instance, you can call itaccept
The method tells it to wait for the connection request to enter. This method will only be returned when there is a connection request. It returnsSocket
Class instance. ThisSocket
The object can then be used to send and receive byte streams from the client program, as explained in the socket class. In fact, in the program included in this articleaccept
The method is the only method used.
The Application
Our web server program is located in the packageex01.pyrmont,
By
3
Classes
:
HttpServer
Request
Response
The staticmain
Method) inHttpServer
Class. It createsHttpServer
Instance and call itsawait
Method. As the name impliesawait
Wait for the HTTP request, process the request, and send a response to these clients. It will wait until it receives a close command. (The method name is usedawait
Insteadwait
Becausewait
YesSystem.Object
A very important method for processing multithreading .)
This program only sends static resources from the specified directory, such as HTML and image files. It does not support headers (such as time or cookies ).
Now, let's take a look at these three classes in the next chapter.
The
HttpServer
Class
HttpServer
Class represents a Web server, which can be provided inWEB_ROOT
The static resources found in the Directory and the static resources under all subdirectories in the directory.WEB_ROOT
Perform initialization as follows:
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";
The above code containsWebrootDirectory, including some static resources used to test this program. You will also find a servlet, which will be used in my next article, "How servlet containers work ."
To request a static resource, enter the following URL in your browser address bar:
http://machineName:port/staticResource
If you run your program and send a request on another machinemachineName
Is the name or IP address of the computer that runs the program. If your browser is on the same machine, you can uselocalhost
AsmachineName
The. Port is 8080,staticResource
Is the name of the file to be requested, and the file must be located inWEB_ROOT
.
For example, if you use the same computer to test the program and you wantHttpServer
ReturnIndex.htmlFile, using the following URL:
http://localhost:8080/index.html
To stop the server, enter the pre-defined closed string in the address bar to send the close command.HttpServer
Class is definedSHUTDOWN
Static final variable:
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
To disable the server, you can use:
http://localhost:8080/SHUTDOWN
Now let's take a look atawait
Method. The explanation of the Code is following this listing.
Listing 1.1.HttpServer
Class'await
Method
public void await() {
ServerSocket serverSocket = null;
int port = 8080;
try {
serverSocket = new ServerSocket(port, 1,
InetAddress.getByName("127.0.0.1"));
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// Loop waiting for a request
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
// create Request object and parse
Request request = new Request(input);
request.parse();
// create Response object
Response response = new Response(output);
response.setRequest(request);
response.sendStaticResource();
// Close the socket
socket.close();
//check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
await
CreateServerSocket
Instance, and then enterwhile
Loop.
serverSocket = new ServerSocket(
port, 1, InetAddress.getByName("127.0.0.1"));
...
// Loop waiting for a request
while (!shutdown) {
...
}
While loop inServerSocket
Of
accept
Stop at Method
This method returns a socket object only when an HTTP request is received on port 8080:
socket = serverSocket.accept();
After receiving a request,await
Method slave