回显主页和favicon

发布时间 2023-03-31 14:42:52作者: 钟离专属

回显主页和favicon

 

找一个图片

 

 

 

写index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主页</title>
</head>
<body>
<h1>主页</h1>
<hr>
</body>
</html>

 

写一个Request类

package web;

/**
 * 请求类
 */
public class Request {
    private String method;
    private String uri;


    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }
}

 

package web;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyHttpServer {

    private static int count = 1;
    private static char arr[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

    public static void main(String[] args) throws IOException {
        byte b = 0x3f;
        byte2(b);
        ServerSocket server = new ServerSocket(8080);
        System.out.println("服务器已经启动,监听端口在8080...");
        while (true){
            Socket socket = server.accept();
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            byte[] buf = new byte[1024*1024];
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int len = 0;
                    try {
                        len = is.read(buf);
                        if (len == -1) return;
                        System.out.println("读到的字节数量是:"+len);
                        String hexMsg = bytes2(buf, len);
                        System.out.println(hexMsg);
                        String s = new String(buf,0,len);
                        System.out.println(s);
                        Request request = parseRequest(s);
                        // HTTP1.1协议 状态码200 正确 回车换行
                        String line1 = "HTTP/1.1 200 OK\r\n";
                        // 内容的类型是普通文本,回车换行
                        String line2 = "Content-Type:text/plain\r\n";
                        // 回车换行
                        final String line3 = "\r\n";
                        String file = null;
                        if (request.getUri().equals("/") || request.getUri().equals("/index.html")){
                            line2 = "Content-Type:text/html\r\n";
                            file = "index.html";
                        }else  if (request.getUri().equals("/favicon.ico")){
                            line2 = "Content-Type: image/x-icon\r\n";
                            file = "favicon.ico";

                        }
                        // 固定的响应三行
                        os.write(line1.getBytes());
                        os.write(line2.getBytes());
                        os.write(line3.getBytes());
                        // 如果file不为空,说明需要回文件给浏览器
                        if (file != null){
                            FileInputStream fis = new FileInputStream(file);
                            while ((len=fis.read(buf)) !=-1){
                                os.write(buf,0,len);
                            }
                        }else {
                            // 返回浏览器的文本内容
                            os.write((""+count).getBytes());
                            count++;
                        }
                        // 主动刷新一次
                        os.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if (socket != null){
                            try {
                                // 关闭资源
                                socket.close();
                            }catch (IOException e){
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }).start();
        }
    }
    /**
     * 解析封装为Request对象
     * @param
     * @return
     */
    private static Request parseRequest(String s){
        Request req = new Request();
        String[] split = s.split("\r\n");
        String[] spl = split[0].split(" ");
        req.setMethod(spl[0]);
        req.setUri(spl[1]);
        return req;
    }

    private static String bytes2(byte[] buf,int len){
        StringBuffer sBuffer = new StringBuffer();
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        int cnt = 0;
        for(int i=0;i<len;i++){
            sb1.append(byte2(buf[i]) + " ");
            if (buf[i] >= 0x20 && buf[i] <= 0x7e){
                sb2.append((char)buf[i]);
            }else {
                sb2.append(".");
            }
            cnt++;
            if (cnt % 8 == 0) sb1.append(" ");
            if (cnt % 16 == 0) {
                sBuffer.append(sb1).append(sb2).append("\r\n");
                 sb1 = new StringBuffer();
                 sb2 = new StringBuffer();
                cnt = 0;
            }
        }
        if (cnt != 0) sBuffer.append(sb1).append("  ").append(sb2).append("\r\n");
        return sBuffer.toString();
    }
    private static String byte2(byte bt){
        int lo = bt & 0b00001111;
        int hi = (bt & 0b11110000) >> 4;//位移运算符 移四位,得到四个1
        char clo = arr[lo];
        char chi = arr[hi];
        return chi+ "" + clo;
    }
}