思路
- 启动Socket服务,循环接收浏览器请求
- 接收到请求之后,将流中的数据取出
- 判断目标资源是否存在,若不存在,返回404
- 若存在,将目标资源通过输出流响应给客户端
类
- Server 开启Socket服务
- Request 封装请求,处理请求的相关业务
- Response 封装响应,处理相应的相关业务
- Test 测试类
Test类
public class Test {
public static void main(String[] args) {
System.out.println("Server startup successfully");
MyHttpServer myHttpServer = new MyHttpServer();
myHttpServer.receiving();
}
}
MyHttpServer类
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyHttpServer {
private int port = 8080;
public void receiving() {
try {
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
System.out.println(inputStream);
MyHttpRequest request = new MyHttpRequest(inputStream);
request.parse();
OutputStream outputStream = socket.getOutputStream();
MyHttpResponse response = new MyHttpResponse(outputStream);
response.sendResponse(request.getUri());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyHttpRequest类
import java.io.IOException;
import java.io.InputStream;
public class MyHttpRequest {
private InputStream inputStream;
private String uri;
public MyHttpRequest(InputStream inputStream) {
this.inputStream = inputStream;
}
public void parse() {
try {
byte[] bytes = new byte[1024];
inputStream.read(bytes);
String request = new String(bytes);
parseUri(request);
} catch (IOException e) {
e.printStackTrace();
}
}
public void parseUri(String request) {
int index1, index2;
index1 = request.indexOf(' ');
index2 = request.indexOf(' ', index1 + 1);
uri = request.substring(index1 + 1, index2);
System.out.println(uri);
}
public String getUri() {
return this.uri;
}
}
MyHttpResponse类
import java.io.*;
public class MyHttpResponse {
private OutputStream outputStream;
public MyHttpResponse(OutputStream outputStream) {
this.outputStream = outputStream;
}
public void sendResponse(String uri) {
String path = System.getProperty("user.dir") + "/001java/WebContent" + uri;
File file = new File(path);
if (file.exists()) {
try {
byte[] bytes = new byte[(int)file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(bytes);
String result = new String(bytes);
String response = getResponseMessage("200", result);
this.outputStream.write(response.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
String error = getResponseMessage("404", " File Not Found!");
System.out.println(error);
try {
this.outputStream.write(error.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getResponseMessage(String code, String message) {
return "HTTP/1.1" + code + "\r\n"
+ "Content-Type: text/html\r\n"
+ "Content-Length: " + message.length()
+ "\r\n"
+ "\r\n"
+ message;
}
}
文件目录

访问存在文件

访问不存在文件
