Java-based web server work mechanism (2)

zhaozj2021-02-16  61

Serversocket class

The Socket class represents the client's socket. Whenever you want to connect to a remote server app, you have to build a socket. If you want to execute a server application, such as an HTTP service or a program, you need to use a different way. Because your server must have always started idle, it doesn't know when the client tries to connect it.

At this time, you need to use the Java.Net.Serversocket class. It implements a server socket. One server Socket will wait for a connection from the client. Once it receives a connection request, it creates a socket instance to handle the problem with client communication.

To create a server socket, you can use one of the four ServerSocket class constructors. You need to develop the IP address and port listening of the server socket. Typical, IP addresses If it is 127.0.0.1, it means that the server socket will monitor the local machine. This listened IP address is considered a binding address. Another important attribute of Server Socket is its backlog property, which is the maximum queue length that can be accepted before the Server Socket denied the connection request.

One of the constructor of the ServerSocket class is as follows:

Public ServerSocket (INT Port, Int Backlog, inetaddress bindingaddress);

For this constructor, the binding address must be an instance of java.net.inetadDress. A simple approach is to construct an inetaddres object by calling its static method getByname. This method comes to a string parameter containing hostname:

Inetaddress.getbyName ("127.0.0.1");

The following line code constructs a serversocket, which monks the 8080 port of the local machine, and the backlog is set to 1.

New Serversocket (8080, 1, inetaddress.getbyname);

Once there is a serversocket instance, you can tell it to wait in the connection request by calling the Accept method. This method only returns when there is a connection request. It returns an instance of the Socket class. This Socket object can send and accept the byte stream from the client application, which is the Socket class that is told in the first section. In fact, Accept is the only way mentioned in this article.

Application application

Our web server application is part of the EX01.PYRMont package, including three classes:

HTTPSERVER Request Response

The application of this application is an HTTPSERVER class. It creates an HTTPSERVER instance to call its AWAIT method. As this method is implied, the AWAIT method waits for an HTTP request in a specified port and processes them, and then sends a response to the client. It keeps waiting until a shutdown command is received. (Command AWAIT replace WAIT is WAIT is an important method for threads in the System.Object class)

Applications only send static resources, such as HTML and image files from a specific directory. Dynamic headers (such as dates or cookies are not supported.

In the following paragraph, let's take a look at these three classes.

HTTPSERVER class

The HTTPServer class represents a web server and serves those static resources found in public static directory web_root and its subdirectory. Web_root initializes:

Public static final string web_root =

System.getProperty ("user.dir") file.seParetor "Webroot"; this code indicates a Webroot directory that contains static resources, which can be used to test the app. A servlet container can also be found in this directory.

To request a static resource, enter the following address or URL in the browser:

Http://machinename: port / staticResource

MachineName is a computer name or IP address running this application. If your browser is on the same machine, you can use localhost as the machine name. The port is 8080. StaticResource is the requesting folder name, which must be in the web-root directory.

If you use the same computer to test the application, you want to send an index.html file to the HTTPSERVER request, then use the following URL:

Http: // localhost: 8080 / index.html

If you want to stop the server, you can send a shutdown command. This command is defined by the static shutdown_command variable in the HTTPServer class:

Private static final string shutdown_command = "/ shutdown";

So, to stop the service, you can use the command:

Http: // localhost: 8080 / shutdown

Let us now take a look at the AWAIT method mentioned earlier. A list of procedures below gives an explanation.

Listing 1.1. The 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 commnd

Shutdown = Request.geturi (). Equals (shutdown_command);

}

Catch (Exception E) {

E.PrintStackTrace ();

CONTINUE;

}

}

}

The AWAIT method starts by creating a Serversocket instance. Then it enters a while loop:

Serversocket = New ServerSocket

Port, 1, inetaddress.getbyname ("127.0.0.1"));

...

// Loop Waiting for a Request

While (! shutdown) {

...

}

Socket = serversocket.accept ();

After receiving a request, the AWAIT method gets java.io.InputStream and Java.Io.OrputStream objects from the Socket instance returned from the Accept method.

INPUT = Socket.getinputStream ();

Output = socket.getOutputStream ();

AWAIT then creates an REQUEST object and calls its Parse method to resolve the original HTTP request information.

// CREATE Request Object and Parse

Request Request = New Request (INPUT);

Request.parse ();

Next, the AWAIT method creates a Response object, using the setRequest method and calls its SendStaticResource method.

// CREATE RESPONSE OBJECT

Response response = new response (OUTPUT);

Response.setRequest (Request);

Response.sendStaticResource ();

Finally, AWAIT closed this socket. Call the Request's geturi method to check if the HTTP request is a shutdown command. If so, the shutdown variable is set to True, and the program exits the While loop.

// Close the socket

Socket.close ();

// Check if the previous Uri is a shutdown commnd

Shutdown = Request.geturi (). Equals (shutdown_command);

转载请注明原文地址:https://www.9cbs.com/read-24926.html

New Post(0)