知识库 tomcat-A Simple Web Server static

来源:互联网 发布:c语言可视化编程软件 编辑:程序博客网 时间:2024/06/05 04:09

1 应用之间的通信
To send byte streams, you must first call the Socket class’s getOutputStream method to obtain a java.io.OutputStream object. To send text to a remote application, you often want to construct a java.io.PrintWriter object from the OutputStream object returned. To receive byte streams from the other end of the connection, you call the Socket class’s getInputStream method that returns a java.io.InputStream.

The Application

Example :consists of three classes: HttpServer、Request、 Response
It also displays the incomings HTTP request byte streams on the console. However ,it doest not send any header, such as dates or cookies, to the browser.

The HttpServer Class

code

This web server can serve static resources found in the directory indicated by the public static final WEB_ROOT and all subdirectories under it.WEB_ROOT is initialized as follows:

public static final String WEB_ROOT = System.getProperty(“user.dir”) + File.separator + “webroot”;

The code listings include a directory called webroot that contains some static resources that you can use for testing this application. You can also find several servlets in the same directory for testing applications in the next chapters.

To request for a static resource, you type the following URL in your browser’s Address or URL box:

http://machineName:port/staticResource

If you are sending a request from a different machine from the one running your application, machineName is the name or IP address of the computer running this application. If your browser is on the same machine, you can use localhost for the machineName.port is 8080 and staticResource is the name of the file requested and must reside in WEB_ROOT.

For instance, if you are using the same computer to test the application and you want to ask the HttpServer object to send the index.html file,you use the following URL.

http://localhost:8080/index.html

To stop the server, you send a shutdown command from a web browser by typing the pre-defined string in the browser’s Address or URL box,after the host:port section of the URL. The shutdown command is defined by the SHUTDOWN static final variable in the HttpServer class:

private static final String SHUTDOWN_COMMAND = “/SHUTDOWN”;

Therefore, to stop the server,you use the following URL:

http://localhost:8080/SHUTDOWN

The method name await is used instead of wait because wait is an important method in the java.lang.Object class for working with threads.

The await method starts by creating an instance of ServerSocket and then going into a while loop.

The code inside the while loop stops at the accept method of ServerSocket,which returns only when an HTTP request is received on port 8080:
socket = serverSocket.accept();
Upon receiving a request, the await method obtains java.io.InputStream and java.io.OutputStream objects from the Socket instance returned by the accept method.
input = socket.getInputStream();
output=socket.getOutputStream();

The await method then creates an Request object and calls its parse method to parse the HTTP request raw data.
//create Request object and parse
Request request = new Request(input);
request.parse();

Afterwards, the await method creates a Response object,sets the Request object to it,and calls its sendStaticResource method.

//create Reponse objectResponse response = new Response(output);response.setRequest(request);response.sendStaticResource();

Finally,the await method closes the Socket and calls the getUri method of Request to check if the URI of the HTTP request is a shutdown command.
If it is,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 command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);

2 The Request Class

Socket handles the communication with the client. You call one of read methods of the InputStream object to obtain the HTTP request raw data.

HTTP协议返回 获取URI=index.html
GET /index.html HTTP/1.1

An example of an HTTP request is the following:

POST /examples/default.jsp HTTP/1.1
Accept: text/plain; text/html
Accept-Language: en-gb
Connection: Keep-Alive
Host: localhost
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

The following is an example of an HTTP response:

HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Date: Mon, 5 Jan 2004 13:13:33 GMT
Content-Type: text/html
Last-Modified: Mon, 5 Jan 2004 13:13:12 GMT
Content-Length: 112



HTTP Response Example


Welcome to Brainy Software

为自尊的生存 路上的辛酸 已融进我的眼睛

Running the Application

To run the application,from the working directory,type the following:

java HttpServer

To test the application, open your browser and type the following in the URL or Address box:

http://localhost:8080/index.html

HttpServer:
package com.qunar.finance.paper.tomcat;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
* Class description
* Created with IntelliJ IDEA
* User :zww.zhang
* Date:2016/11/13
*/
public class HttpServer {
/**
* WEB_ROOT is the directory where our HTML and other files reside
* For this package, WEB_ROOT is the “webroot” directory under the working
* directory. The working directory is the location in the file system from
* where the java command was invoked.
*/

public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";//shutdown commandprivate static final String SHUTDOWN_COMMAND = "/SHUTDOWN";//the shutdown command receivedprivate boolean shutdown = false;public static void main(String[] args) {    HttpServer server = new HttpServer();    System.out.println(WEB_ROOT);    server.await();}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;//吞掉异常        }    }}

}

Request:

package com.qunar.finance.paper.tomcat;

import java.io.IOException;
import java.io.InputStream;

/**
* Class description
* Created with IntelliJ IDEA
* User :zww.zhang
* Date:2016/11/13
*/
public class Request {
private InputStream input;
private String uri;

public Request(InputStream input) {    this.input = input;}public void parse() {    StringBuffer request = new StringBuffer(2048);    int i;    byte[] buffer = new byte[2048];    try {        i = input.read(buffer);    } catch (IOException e) {        e.printStackTrace();        i = -1;    }    for (int j = 0; j < i; j++) {        request.append((char) buffer[j]);    }    System.out.println(request.toString());    uri = parseUri(request.toString());    System.out.println("uri-- " + uri);}private String parseUri(String requestString) {    int index1, index2;    index1 = requestString.indexOf(' ');    if (index1 != -1) {        index2 = requestString.indexOf(' ', index1 + 1);        if (index2 > index1) {            return requestString.substring(index1 + 1, index2);        }    }    return null;}public String getUri() {    return uri;}

}

Response:

package com.qunar.finance.paper.tomcat;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
* Class description
* Created with IntelliJ IDEA
* User :zww.zhang
* Date:2016/11/13
*/
public class Response {

/** * HTTP Response = Status-Line * ((general-header | response-header|entity-header)CRLF)CRLF * [ message-body] * Status-Line = HTTP-Version SP Status_Code SP Reason-Phrase CRLF */private static final int BUFFER_SIZE = 1024;private Request request;OutputStream output;public Response(OutputStream output) {    this.output = output;}public void setRequest(Request request) {    this.request = request;}public void sendStaticResource() throws IOException {    byte[] bytes = new byte[BUFFER_SIZE];    FileInputStream fis = null;    try {        File file = new File(HttpServer.WEB_ROOT, request.getUri());        if (file.exists()) {            fis = new FileInputStream(file);            int ch = fis.read(bytes, 0, BUFFER_SIZE);            while (ch != -1) {                output.write(bytes, 0, ch);                ch = fis.read(bytes, 0, BUFFER_SIZE);            }        } else {            //file not found            String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +                    "Content-Type:text/html\r\n" +                    "Content-Length:23\r\n" +                    "\r\n" +                    "<h1>File Not Found</h1>";            output.write(errorMessage.getBytes());        }    } catch (Exception e) {        //thrown if cannot instantiate a File object        System.out.println(e.toString());    } finally {        if (fis != null) {            fis.close();        }    }}

}

0 0
原创粉丝点击