java set up a web server

Today in Java implements a simple version of the web server, but there is some question, so far, do not know how to solve.

I put the code and problems here and there to see if big brother, to help solve it.

public class TcpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(4000);
        while(true) {
            Socket socket=server.accept();
            new Thread(()->{
                try {
                    BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String str=br.readLine();
                    String[] strArr=str.split(" ");
                    String path=strArr[1].substring(1);
                    //构造方法中绑定要读取的html路径
                    FileInputStream fis=new FileInputStream(path);
                    int len=0;
                    byte[] b=new byte[1024];
                    OutputStream os=socket.getOutputStream();
                    //写入http协议响应头,固定写法
                    os.write("HTTP/1.1 200 OK\r\n".getBytes());
                    os.write("Content-Type:text/html\r\n".getBytes());
                    //必须写入空行,否则浏览器不解析
                    os.write("\r\n".getBytes());
                    while((len=fis.read(b))!=-1) {
                        os.write(b, 0, len);
                    }
                    fis.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }   
    }
}

Ultimately results

Wrong display

Expected results

Expected results

The following were attached index.html, index.css, index.js code

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我是你爸爸</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <div id="box">我是你爸爸哦<a href="mother.html">点击去找你妈妈</a></div>
    <img src="kitchen.jpg" alt="">
</body>
<script src="index.js"></script>
</html>

index.css
#box {
    font-size:50px;
}

index.js
let $id=document.getElementById("box");
$id.style.color="gold";

By running the results can be seen, js references successfully loaded out, but css references effect is not loaded up.

I do not know why, help!

Personal guess is the result of the implementation of multi-threaded? Should first load css then execute HTML?

Guess you like

Origin www.cnblogs.com/meethigher/p/12151827.html