简单的Web Server Java实现

简单起见,我这个web Server只写了get请求的
一个HTTP请求应该形如
这是百度的https请求

CONNECT www.baidu.com:443 HTTP/1.1
Host: www.baidu.com:443
Proxy-Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36

这是http请求

HTTP请求头 
GET http://xxx:8080/main.html HTTP/1.1
Host: xxx:8080
Proxy-Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1

第一行是GET 或者CONNECT https要建立安全通道

# 主程序
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *  自己实现的一个http服务器
 * @author Administrator
 */
public class Httpserver {
    private static boolean Running =true;
    public static void main(String[] args) {
        // http服务器端口
        int port = 8081 ;
        try {
            ServerSocket httpserver = new ServerSocket(port);
            while (Running){
                Socket socket = httpserver.accept();
                new Thread(new httpThread(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Running = false;
        }
    }
}
# 子线程
import java.io.*;
import java.net.Socket;

public class httpThread implements Runnable {
    private InputStream inputStream;
    private OutputStream outputStream;
    private OutputStreamWriter outputStreamWriter;

    public httpThread(Socket socket) throws IOException {
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();
        outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
    }

    @Override
    public void run() {
        try {
            String path = readHead();
            System.out.println(path);
            response(path);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public void response(String path) throws IOException {
        String relativelyPath = System.getProperties().getProperty("user.dir");
        String path1 = relativelyPath+File.separator+"src\\static";
        File file = new File(path1+path);
        System.out.println(file.exists());
        if(!file.exists()){
            try {
                StringBuffer error = new StringBuffer();
                String html = "<h1>404 File Not Found.</h1>";
                error.append("HTTP/1.1 404 Not Found \r\n");
                error.append("Content-Type:text/html;charset=UTF-8 \r\n");
                error.append("Content-Length:").append(html.length()).append("\r\n").append("\r\n");
                error.append(html);
                outputStreamWriter.write(error.toString());
                outputStreamWriter.flush();
                outputStreamWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            FileInputStream fileInputStream = new FileInputStream(file);
            outputStream.write("HTTP/1.1 200 OK\n".getBytes());
            outputStream.write("Content-Type: text/html; charset=UTF-8\n\n".getBytes());
            byte[]  buffer = new byte[1024];
            int readLength = 0;
            while((readLength = fileInputStream.read(buffer, 0, 1024)) > 0 ) {
                outputStream.write(buffer, 0, readLength);
            }
            outputStream.flush();
            outputStream.close();
        }

    }
    public String readHead() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder header = new StringBuilder();
        String msg = null;
        String location = null;
        while (null != (msg = reader.readLine())) {
            header.append(msg);
            if (msg.length() == 0) {
                break;
            } else {
                String[] temp = msg.split(" ");
                if (temp[0].contains("GET")) {
                    location = temp[1];
                }
            }

        }
        if(location!=null){
            return "\\"+location.substring(1,location.length());
        }
        else {
            return null;
        }
    }
}

发布了22 篇原创文章 · 获赞 2 · 访问量 881

猜你喜欢

转载自blog.csdn.net/weixin_41685373/article/details/103779488