public class MyTomcat {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8887);
while (!serverSocket.isClosed()) {
System.out.println("=====我的web服务在 8887端口监听=====");
Socket socket = serverSocket.accept();
OutputStream outputStream = socket.getOutputStream();
BufferedReader bufferedReader =
new BufferedReader(new FileReader("src/hello1.html"));
String buf = "";
//html文件发送 应该加上头部,使得浏览器能够识别其属性
outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
outputStream.write("Content-Type: text/html;charset=UTF-8\r\n".getBytes());
outputStream.write("\r\n".getBytes());
//读取文件内容
while ((buf = bufferedReader.readLine()) != null) {
outputStream.write(buf.getBytes());
}
System.out.println("完成发送");
outputStream.close();
socket.close();
}
serverSocket.close();
}
}
html文件应该加上如下头部内容,才能被浏览器正常识别
outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
outputStream.write("Content-Type: text/html;charset=UTF-8\r\n".getBytes());
outputStream.write("\r\n".getBytes());
hello1.html文件如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hhh</title>
</head>
<body>
222
</body>
</html>
浏览器访问localhost:8887结果如下,跟html内容对应
如果没有头部内容,则浏览器无法正常打开html文件,返回的结果无效
ps:也可以模拟浏览器在8887端口读取html内容信息
public class testBrowser {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 8887);
String filePath="d:\\1.txt";
FileOutputStream os = new FileOutputStream(filePath);
InputStream inputStream = socket.getInputStream();
byte[] buf=new byte[1024];
int len=0;
while((len=inputStream.read(buf))!=-1){
os.write(buf,0,len);
}
os.close();
inputStream.close();
}
}
没有头部信息读出的结果如下
添加头部信息读出结果如下