2021SC@SDUSC
上篇文章介绍了HTTP源代码中的所有接口类,这篇文章我们来看具体类的实现。
HttpServerConnection
该类代表服务器连接。它可以从 AsyncHttpClient (客户端)接收 HttpRequest(请求)并使用 AsyncServlet<HttpRequest>响应它们。
其构造函数为:
HttpServerConnection(Eventloop eventloop, AsyncTcpSocket asyncTcpSocket, InetAddress remoteAddress,
AsyncHttpServer server, AsyncServlet servlet) {
super(eventloop, asyncTcpSocket, server.maxBodySize);
this.remoteAddress = remoteAddress;
this.server = server;
this.servlet = servlet;
this.inspector = server.inspector;
}
该方法在收到标题行后调用:
protected void onStartLine(byte[] line, int pos, int limit) throws MalformedHttpException {
switchPool(server.poolReadWrite);
HttpMethod method = getHttpMethod(line, pos);
if (method == null) {
if (!DETAILED_ERROR_MESSAGES) throw new MalformedHttpException("Unknown HTTP method");
throw new MalformedHttpException("Unknown HTTP method. First line: " +
new String(line, 0, limit, ISO_8859_1));
}
int urlStart = pos + method.size + 1;
int urlEnd;
for (urlEnd = urlStart; urlEnd < limit; urlEnd++) {
if (line[urlEnd] == SP) {
break;
}
}
int p;
for (p = urlEnd + 1; p < limit; p++) {
if (line[p] != SP) {
break;
}
}
HttpVersion version;
if (p + 7 < limit
&& line[p + 0] == 'H' && line[p + 1] == 'T' && line[p + 2] == 'T' && line[p + 3] == 'P' && line[p + 4] == '/' && line[p + 5] == '1' && line[p + 6] == '.') {
if (line[p + 7] == '1') {
flags |= KEEP_ALIVE; // keep-alive for HTTP/1.1
version = HTTP_1_1;
} else if (line[p + 7] == '0') {
version = HTTP_1_0;
} else {
if (!DETAILED_ERROR_MESSAGES) throw new MalformedHttpException("Unknown HTTP version");
throw new MalformedHttpException("Unknown HTTP version. First line: " +
new String(line, 0, limit, ISO_8859_1));
}
} else {
if (!DETAILED_ERROR_MESSAGES) throw new MalformedHttpException("Unsupported HTTP version");
throw new MalformedHttpException(
"Unsupported HTTP version. First line: " + new String(line, 0, limit, ISO_8859_1));
}
request = new HttpRequest(version, method, UrlParser.parse(line, urlStart, urlEnd), this);
request.maxBodySize = maxBodySize;
if (method == GET || method == DELETE) {
contentLength = 0L;
}
}
onHeader()方法在收到头后调用。它将其值设置为请求。
protected void onHeader(HttpHeader header, byte[] array, int off, int len) throws MalformedHttpException {
if (header == HttpHeaders.EXPECT && equalsLowerCaseAscii(EXPECT_100_CONTINUE, array, off, len)) {
socket.write(ByteBuf.wrapForReading(EXPECT_RESPONSE_CONTINUE));
}
//noinspection ConstantConditions
if (request.headers.size() >= MAX_HEADERS) {
throw new MalformedHttpException("Too many headers");
}
request.addHeader(header, array, off, len);
}
余下的类都是对HTTP中接口的具体实现。如HttpMessage、HttpRequest、HttpResponse等。这里就不过多描述。