我希望在我正在做的Java项目中实现HTTP 1.0和1.1规范。
目前,我能够为服务器创建一个套接字,它将接受客户端套接字并处理来自客户端的查询。处理完查询后,客户端的连接已关闭。
private void start(int port) throws IOException {
System.out.println("Starting server on port " + port);
ServerSocket serverSocket = new ServerSocket(port);
while(true){
Socket clientSocket = serverSocket.accept();
handleClientSocket(clientSocket);
}
}
private void handleClientSocket(Socket client) throws IOException {
String loc = "";
String host = "";
String method = "";
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line;
while(!(line = in.readLine()).isEmpty()){
//Logs ouput.
System.out.println(line);
...//parse input etc.
//form request and send it.
HttpRequest request = new HttpRequest(loc, method, host);
sendHttpResponse(client, formHttpResponse(request));
}
private void sendHttpResponse(Socket client, byte[] response) throws IOException {
System.out.println("Writing");
OutputStream out = client.getOutputStream();
out.write(response);
//close connection.
out.close();
}
这与HTTP 1.0规范一致,因为服务器在查询完成后关闭连接。但是,我不确定如何实现HTTP 1.1规范,因为它需要持久性和管道衬里。
我已经概述了我认为逻辑流程将在下面的逻辑:
这是一个准确的表示吗?如果是这样,我该如何实现端口的超时?