"Depth analysis Tomcat" the first chapter a simple Web server

This chapter describes how Java Web server is running. Where you can know how Tomcat works.

It uses a Java-based Web server java.net.Socket java.net.ServerSocket classes and class two classes, and communicate by sending HTTP messages.

Therefore, this chapter describes the HTTP protocol and the first two classes. Then introduce a simple Web server.

1.1 HTTP protocol

HTTP request and corresponding information

slightly.

1.2 Socket class

1.2.1  the Socket class

Socket class represents a client socket (socket), that is, when you want to create a socket connection to the remote server applications.

public the Socket (String host, int port); // parameter host is the remote host name or IP address, port parameter is the port number to connect remote applications.
// For example, you want to connect yahoo.com, you can create a Socket object with the following statement through port 80: 
new new Socket ( "yahoo.com" 80.);

Upon successful Socket class creates an instance, that instance can be used to send or receive byte stream. Code Example:

package demo;

import java.io.*;
import java.net.Socket;

public class SocketDemo {
    public static void main(String[] args) {
        try {
            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 new the BufferedReader ( new new the InputStreamReader (Socket.getInputStream ()));
             // send a request to the HTTP server 
            Out.println ( "/index.jsp the GET HTTP / 1.1" ); 
            Out.println ( "the Host: localhost: 8080" ) ; 
            Out.println ( "Connection: the Close" ); 
            Out.println (); 
            // read response 
            Boolean Loop = to true ; 
            the StringBuffer SB = new new the StringBuffer (8096 );
             the while (Loop) {
                 IF (in.ready ()) {
                     int I = 0;
                    while (i != -1) {
                        i = in.read();
                        sb.append((char) i);
                    }
                    loop = false;
                }
                Thread.currentThread().sleep(50);
            }
            //展示响应信息
            System.out.println(sb.toString());
            socket.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }


    }
}

got the answer:

The HTTP / 1.1 200 is  
the Content -Type: text / HTML; charset = UTF. 8- 
Transfer - Encoding: chunked 
a Date: Thu, 26 is On Sep 2019 10:21:08 GMT 
Connection: Close

 2000 

(and the Tomcat index.jsp page code)

Server 1.2.2 the Socket class

 Socket class ServerSocket class and not the same. Server socket must always be on standby, it does not know the client application can initiate a connection when. ServerSocket class constructor needs to specify the port number and IP address of the server listening socket.

Wherein a signature ServerSocket class constructor as follows:

public SeverSocket (int port, int backLog, InetAddress bindingAddress);

 

After you create a ServerSocket instance, you can make it wait for an incoming connection requests, the address of the incoming connection requests on port binding listens through a server socket. These can be done by calling the accept method of class ServerSocket. Only when the connection request is received, the method will return, the return value is a Socket instance. Socket object which can be used with the byte stream to the client application sending / receiving.

1.3 Applications

For more knowledge, do a simple web server. HttpServer has launched a class equivalent of Tomcat, Request class analog access URL, Response class analog return messages.

Package Penalty for WebDemo; 

Import java.io. * ;
 Import java.net.InetAddress;
 Import java.net.ServerSocket;
 Import java.net.Socket; 

public  class the HttpServer {
     // WEB_ROOT static resource directory where 
    public  static  Final String WEB_ROOT = 
            System. getProperty ( "user.dir") + the File.separator + "webRoot" ;
     // Close 
    public  static  Final String = SHUTDOWN_COMMAND "/ the SHUTDOWN" ;
     // whether a close instruction 
    Private  Boolean the shutdown = to false;

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
    }

    private void await() {
        ServerSocket serverSocket = null;
        int port = 8081;
        try {
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        } 

        The while (! The shutdown) { 
            the Socket Socket; 
            the InputStream INPUT; 
            a FileOutputStream Output; 

            the try { 
                Socket = serverSocket.accept (); 
                INPUT = Socket.getInputStream (); 
                Output = (a FileOutputStream) Socket.getOutputStream ();
                 // Create the request Object parameters and 
                the Request = Request new new the Request (INPUT); 
                request.parse (); 
                // Create an object in response to 
                the response response = new new the response (Output);
                response.setRequest(request);
                response.sendStaticResource();
                // 关闭Socket
                socket.close();
                // 如果URL是shutdown命令
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
            } catch (Exception e) {
                e.getStackTrace();
                continue;
            }
        }
    }
}
package webDemo;

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

public class Request {
    private InputStream input;
    private String uri;

    public Request(InputStream input) {
        this.input = input;
    }

    public String getUri() {
        return uri;
    }

    /**
     *  从InputStream对象中读取整个字节流
     */
    public void parse() {
        StringBuffer request = new StringBuffer(2048);
        int i;
        byte[] buffer = new byte[2048];
        try {
            i = input.read(buffer);
        } catch (IOException e) {
            e.getStackTrace();
            i = -1;
        }
        for (int j = 0; j < i; j++) {
            request.append((char) buffer[j]);
        }
        System.out.println("request == " + request.toString());
        uri = parseUri(request.toString());
    }

    / ** 
     * the GET /index.html the HTTP / 1.1 
     * This method searches for the first and second spaces in the request line, in order to identify the URI 
     * @param requestString 
     * @return 
     * / 
    Private String ParseUri (String requestString) {
         int index1,;
         int index2 = 0 ; 
        index1, = requestString.indexOf ( '' );
         IF (index1, = -1! ) { 
            index2 = requestString.indexOf ( '', index1, +. 1 ); 
        } 
        IF (index2> index1,) {
             return requestString.substring (index1, +. 1 , index2);
        }
        return null;
    }
}
package webDemo;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/*
    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
 */
public class Response {
    Request request;
    OutputStream output;

    public Response(OutputStream output) {
        this.output = output;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    /**
     * 发送静态资源
     * @throws IOException
     */
    public void sendStaticResource() throws IOException {
        try {
            File file = new File(HttpServer.WEB_ROOT, request.getUri());//目录+文件名
            if (file.exists()) {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\r\n");
                }
                StringBuffer result = new StringBuffer();
                result.append("HTTP/1.1 200 ok \r\n");
                result.append("Content-Language:zh-CN \r\n");
                // charset=UTF-8 解决中文乱码问题
//                result.append("Content-Type:text/html;image/gif;charset=UTF-8 \r\n");
                result.append("multipart/x-mixed-replace; boundary=myboundary");
                result.append("Content-Length:" + file.length() + "\r\n");
                result.append("\r\n" + sb.toString());
                output.write(result.toString().getBytes());
                output.flush();
                output.close();
            } else {
                //如果没有文件
                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) {
            System.out.println("----" + e.toString());
        }
    }

    private void covertImag(String line) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(line);
            for (int i = 0; i < b.length; i++) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            output.write(b);
            output.flush();
            output.close();
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }
}

 index.html page code:

<html>
    <head>
        <title>Welcome to BrainySoftware</title>
    </head>
    <body>
        <img src="./images/logo.gif">
        <br>
        Welcome to BrainySoftware.
    </body>
</html>

The html page contains a picture, but my code does not display the code, temporarily did not find a solution, keep after the pit fill. If God knows how to handle a large, very grateful to be able to teach me.

Guess you like

Origin www.cnblogs.com/tzzt01/p/11596114.html