我正在处理 Java 中的 HTTP 和套接字,希望你能对此有所了解:
当我用 Java SE 11 编写的 HTTP 服务器没有读取整个请求然后响应时,客户端没有得到它或得到一个错误。这是为什么?在服务器读取整个请求之前,客户端是否无法读取响应?如果在下面的代码段中执行了对 readBody 的调用,这可以正常工作。如果响应具有 Content-Length 标头和文本正文,它也能正常工作。这对我来说实际上更令人费解。
我的示例请求是带有数据fds的 POST 。邮递员说“无法获得任何请求”,curl 说“curl:(56) 接收失败:对等方重置连接”。
import java.io.*;
import java.net.Socket;
import java.util.*;
class Handler {
public synchronized void read(Socket incoming) {
try (incoming;
OutputStream outputStream = incoming.getOutputStream();
InputStream inputStream = incoming.getInputStream();
PrintWriter pw = new PrintWriter(outputStream)) {
writeRequest(inputStream);
pw.print("HTTP/1.1 200 OK\r\n");
pw.print("\r\n");
pw.flush();
} catch (IOException e) {
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
}
private void writeRequest(InputStream inputStream) throws IOException {
String verbLine = readLine(inputStream);
Map<String, String> headers = readHeaders(inputStream);
//readBody(inputStream, headers);
}
private void readBody(InputStream inputStream, Map<String, String> headers) throws IOException {
Optional<String> optKey = headers.keySet().stream()
.filter(k -> k.equalsIgnoreCase("Content-Length"))
.findFirst();
if (optKey.isPresent()) {
int contentLength = Integer.parseInt(headers.get(optKey.get()));
byte[] bytes = inputStream.readNBytes(contentLength);
}
}
private Map<String, String> readHeaders(InputStream inputStream) throws IOException {
Map<String, String> headers = new HashMap<>();
while (true) {
String line = readLine(inputStream);
if (line == null || line.isEmpty()) {
return headers;
}
String key = line.split(":")[0].trim();
String value = line.split(":")[1].trim();
headers.put(key, value);
}
}
private String readLine(InputStream inputStream) throws IOException {
byte[] buf = new byte[200];
int offset = 0;
while (true) {
int read = inputStream.read();
if (read == -1) {
return null;
}
buf[offset] = (byte) read;
if (buf[0] == '\n' || (buf[0] == '\r' && buf[1] == '\n')) {
return "";
}
if (buf[offset] == 0x0A) {
int endOfLine = buf[offset - 1] == 0x0D ? offset - 1 : offset;
return new String(buf, 0, endOfLine);
} else {
offset++;
}
}
}
}
如果在仍有未读数据的情况下关闭服务器上的套接字,则会导致客户端出现连接重置错误。这是因为您没有阅读完整的请求。如果尚未读取来自服务器的完整响应,则会向用户公开此错误。
如果您使用 a 发送响应,content-length
然后发送完整的正文,则客户端将读取完整的响应,因此将忽略错误。相反,如果您既不发送content-length
也不使用分块编码,则客户端将期望响应以 TCP 连接的正确关闭结束。在这种情况下,连接重置将传播给用户,因为尚未(正确)读取来自服务器的完整响应。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句