Simple Implementation Process Record of java Server

  • 2021-12-13 08:14:05
  • OfStack

Catalog 1. HTTP2 socket Class 3 Server Application Implementation Summary

1. HTTP

http Request

A 1 http request consists of the following three parts:

1 request methods, such as get, post

2 request header

3 Entities

An example of an http request is as follows:

GET /index.jsp HTTP/1.1

Host: localhost:8080

User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: keep-alive

Notice the url in the red part, which we will intercept later.

http response

Similar to the http request, the http response consists of three parts

1 Protocol-Status Code-Description

2 response header

3 Response Entity Segment

2 socket class

A socket is a breakpoint of a network connection. Sockets enable applications to read data from and write data to the network. Applications on different computers can send or receive byte streams through sockets. The Socket class is provided in java to realize this function, and the input and output streams in the network can be obtained through getInputStream and getOutputStream.

However, the Socket class alone can't realize the function of building a server application, because the server must be on standby at all times, so ServerSocket class is provided in java to handle the request waiting from the client. When ServerSocket receives the request from the client, it will create an instance to handle the communication with the client.

Implementation of 3 server application program

First, we need to build a class requst that encapsulates the request information, a class response that responds to the request, and a main program httpServer to handle the request from the client.


package com.lwq;

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

/**
 * @author Joker
 *  Class description 
 *  Convert the request information sent by the browser into characters and intercept url
 */
public class Request {
    
    // Input stream 
    private InputStream input;
    // Interception url, Such as http://localhost:8080/index.html  The intercepted part is  /index.html
    private String uri;
    public Request(InputStream inputStream){
        this.input = inputStream;
    }
    
    public InputStream getInput() {
        return input;
    }
    public void setInput(InputStream input) {
        this.input = input;
    }
    public String getUri() {
        return uri;
    }
    public void setUri(String uri) {
        this.uri = uri;
    }
    
    // Read character information from a socket 
    public void parse(){
        
            StringBuffer request = new StringBuffer(2048);
            int i = 0;
            byte[] buffer = new byte[2048];
            
            try {
                i = input.read(buffer);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                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());
            }
    // Intercept the requested url
    private String parseUri(String requestString){
        
        int index1 = 0;
        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;
    }  
    }

The following is the class response that encapsulates the response request:


package com.lwq;

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

/**
 * @author Joker
 * @version  Creation time: Sep 5, 2012 9:59:53 PM
 *  Class description   Return the result according to the corresponding information 
 */
public class Response {
    
    private static final int BUFFER_SIZE = 1024;
    Request request;
    OutputStream output;
    public Response(OutputStream output){
        this.output = output;
    }
    
    public void sendStaticResource() throws IOException{
        
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        
        File file = new File(HttpServer.WEB_ROOT,request.getUri());
        if(file.exists()){
            try {
                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);
                }
                
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                if(fis !=null){
                    fis.close();
                }
            }
            
        }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" +
     "
File Not Found
";
             try {
                output.write(errorMessage.getBytes());
                output.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public Request getRequest() {
        return request;
    }
    public void setRequest(Request request) {
        this.request = request;
    }
    public OutputStream getOutput() {
        return output;
    }
    public void setOutput(OutputStream output) {
        this.output = output;
    }
    public static int getBUFFER_SIZE() {
        return BUFFER_SIZE;
    }
}

Next is the main program,


package com.lwq;

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

/**
 * @author Joker
 *  Class description 
 */
public class HttpServer {

    /**
     * @param args
     */
    
    //WEB_ROOT Is the root directory of the server 
    public static final String WEB_ROOT = System.getProperty("user.dir")+File.separator+"webroot";
    
    // Close command 
    private static final String SHUTDOWN_COMMAND= "/SHUTDOWN";
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HttpServer server = new HttpServer();
        server.await();

    }
    public void await(){
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            serverSocket = new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
            while(true)
            {
                try {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            socket = serverSocket.accept();
            input = socket.getInputStream();
            output = socket.getOutputStream();
            // Encapsulation request Request 
            Request request = new Request(input);
            request.parse();
            // Encapsulation response Object 
            Response response = new Response(output);
            response.setRequest(request);
            response.sendStaticResource();
            socket.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    continue;
                }
            
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        
    }
    

}

Run httpServer and type http://localhost: 8080/index. jsp in the browser, and you can see the result of the server response.

Summarize


Related articles: