support for keep-alive and close connections
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
package org.lumijiez.core.http;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface HttpHandler {
|
||||
void handle(HttpRequest request, HttpResponse response);
|
||||
void handle(HttpRequest request, HttpResponse response) throws IOException;
|
||||
}
|
||||
@@ -1,42 +1,52 @@
|
||||
package org.lumijiez.core.http;
|
||||
|
||||
import org.lumijiez.logging.Logger;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpRequest {
|
||||
private String method;
|
||||
private String path;
|
||||
private String httpVersion;
|
||||
private final Map<String, String> headers;
|
||||
|
||||
public HttpRequest(BufferedReader in) throws IOException {
|
||||
this.headers = new HashMap<>();
|
||||
parseRequest(in);
|
||||
}
|
||||
|
||||
private void parseRequest(BufferedReader in) throws IOException {
|
||||
String requestLine;
|
||||
|
||||
while ((requestLine = in.readLine()) != null) {
|
||||
|
||||
if (!requestLine.trim().isEmpty()) {
|
||||
String[] tokens = requestLine.split(" ");
|
||||
if (tokens.length == 3) {
|
||||
this.method = tokens[0];
|
||||
this.path = tokens[1];
|
||||
this.httpVersion = tokens[2];
|
||||
break;
|
||||
} else {
|
||||
Logger.error("HTTP", "Invalid line format: " + requestLine);
|
||||
throw new IOException("Invalid request line format.");
|
||||
}
|
||||
String requestLine = in.readLine();
|
||||
if (requestLine != null && !requestLine.trim().isEmpty()) {
|
||||
String[] tokens = requestLine.split(" ");
|
||||
if (tokens.length == 3) {
|
||||
this.method = tokens[0];
|
||||
this.path = tokens[1];
|
||||
this.httpVersion = tokens[2];
|
||||
} else {
|
||||
throw new IOException("Invalid request line format.");
|
||||
}
|
||||
}
|
||||
|
||||
// String headerLine;
|
||||
// while ((headerLine = in.readLine()) != null && !headerLine.trim().isEmpty()) {
|
||||
// Logger.info("HTTP-DEBUG", "Header: " + headerLine);
|
||||
// }
|
||||
String headerLine;
|
||||
while ((headerLine = in.readLine()) != null && !headerLine.trim().isEmpty()) {
|
||||
int separator = headerLine.indexOf(':');
|
||||
if (separator > 0) {
|
||||
String key = headerLine.substring(0, separator).trim().toLowerCase();
|
||||
String value = headerLine.substring(separator + 1).trim();
|
||||
headers.put(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isKeepAlive() {
|
||||
String connection = headers.get("connection");
|
||||
if ("close".equalsIgnoreCase(connection)) {
|
||||
return false;
|
||||
}
|
||||
return "HTTP/1.1".equals(httpVersion) ||
|
||||
"keep-alive".equalsIgnoreCase(connection);
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
|
||||
@@ -2,22 +2,44 @@ package org.lumijiez.core.http;
|
||||
|
||||
import org.lumijiez.logging.Logger;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
|
||||
public class HttpResponse {
|
||||
private final PrintWriter out;
|
||||
private final BufferedWriter out;
|
||||
|
||||
public HttpResponse(PrintWriter out) {
|
||||
public HttpResponse(BufferedWriter out) {
|
||||
this.out = out;
|
||||
}
|
||||
|
||||
public void sendResponse(int statusCode, String message) {
|
||||
public void sendResponse(int statusCode, String message) throws IOException {
|
||||
Logger.info("HTTP", "Outgoing: " + statusCode + " " + message);
|
||||
out.println("HTTP/1.1 " + statusCode + " " + message);
|
||||
out.println("Content-Type: text/plain");
|
||||
out.println("Connection: close");
|
||||
out.println();
|
||||
out.println(message);
|
||||
|
||||
out.write("HTTP/1.1 " + statusCode + " " + getStatusText(statusCode));
|
||||
out.write("\r\n");
|
||||
|
||||
out.write("Content-Type: text/plain");
|
||||
out.write("\r\n");
|
||||
out.write("Content-Length: " + message.getBytes("UTF-8").length);
|
||||
out.write("\r\n");
|
||||
out.write("Connection: keep-alive");
|
||||
out.write("\r\n");
|
||||
out.write("Keep-Alive: timeout=30");
|
||||
out.write("\r\n");
|
||||
|
||||
out.write("\r\n");
|
||||
|
||||
out.write(message);
|
||||
|
||||
out.flush();
|
||||
}
|
||||
|
||||
private String getStatusText(int code) {
|
||||
return switch (code) {
|
||||
case 200 -> "OK";
|
||||
case 404 -> "Not Found";
|
||||
case 500 -> "Internal Server Error";
|
||||
default -> "Unknown";
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,10 @@ package org.lumijiez.core.http;
|
||||
import org.lumijiez.core.routing.Router;
|
||||
import org.lumijiez.logging.Logger;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.*;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@@ -19,6 +17,10 @@ public class HttpServer {
|
||||
private final ExecutorService threadPool;
|
||||
private final Router router;
|
||||
|
||||
private static final int KEEP_ALIVE_TIMEOUT = 30000;
|
||||
private static final int MAX_REQUESTS_PER_CONNECTION = 1000;
|
||||
private static final int BUFFER_SIZE = 8192;
|
||||
|
||||
public HttpServer(int port) {
|
||||
this.running = false;
|
||||
this.port = port;
|
||||
@@ -63,39 +65,75 @@ public class HttpServer {
|
||||
|
||||
protected void handleClient(Socket clientSocket) {
|
||||
try {
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||
clientSocket.setSoTimeout(KEEP_ALIVE_TIMEOUT);
|
||||
|
||||
in.mark(32000);
|
||||
if (!in.ready()) {
|
||||
clientSocket.close();
|
||||
return;
|
||||
BufferedReader in = new BufferedReader(
|
||||
new InputStreamReader(clientSocket.getInputStream()),
|
||||
BUFFER_SIZE
|
||||
);
|
||||
BufferedWriter out = new BufferedWriter(
|
||||
new OutputStreamWriter(clientSocket.getOutputStream()),
|
||||
BUFFER_SIZE
|
||||
);
|
||||
|
||||
int requestCount = 0;
|
||||
boolean keepAlive = true;
|
||||
|
||||
while (keepAlive && requestCount < MAX_REQUESTS_PER_CONNECTION && running) {
|
||||
try {
|
||||
if (!in.ready()) {
|
||||
Thread.sleep(10);
|
||||
continue;
|
||||
}
|
||||
|
||||
HttpRequest request = new HttpRequest(in);
|
||||
if (request.getMethod() == null || request.getPath() == null) {
|
||||
break;
|
||||
}
|
||||
|
||||
HttpResponse response = new HttpResponse(out);
|
||||
|
||||
Logger.info("HTTP", String.format(
|
||||
"Incoming [%d]: %s %s (keep-alive: %s)",
|
||||
requestCount + 1,
|
||||
request.getMethod(),
|
||||
request.getPath(),
|
||||
request.isKeepAlive()
|
||||
));
|
||||
|
||||
router.handleRequest(request, response);
|
||||
|
||||
keepAlive = request.isKeepAlive();
|
||||
requestCount++;
|
||||
|
||||
out.flush();
|
||||
|
||||
} catch (SocketTimeoutException e) {
|
||||
Logger.info("HTTP", "Keep-alive timeout reached");
|
||||
break;
|
||||
} catch (InterruptedException e) {
|
||||
Logger.info("HTTP", "Connection handling interrupted");
|
||||
break;
|
||||
} catch (IOException e) {
|
||||
if (running) {
|
||||
Logger.error("HTTP", "Error processing request: " + e.getMessage());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
String firstLine = in.readLine();
|
||||
if (firstLine == null || firstLine.trim().isEmpty()) {
|
||||
clientSocket.close();
|
||||
return;
|
||||
}
|
||||
in.reset();
|
||||
|
||||
HttpRequest request = new HttpRequest(in);
|
||||
HttpResponse response = new HttpResponse(out);
|
||||
|
||||
if (request.getMethod() != null && request.getPath() != null) {
|
||||
Logger.info("HTTP", "Incoming: " + request.getMethod() + " " + request.getPath());
|
||||
router.handleRequest(request, response);
|
||||
}
|
||||
|
||||
clientSocket.close();
|
||||
} catch (IOException e) {
|
||||
Logger.error("HTTP", "Error handling client: " + e.getMessage());
|
||||
if (running) {
|
||||
Logger.error("HTTP", "Error handling client: " + e.getMessage());
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
clientSocket.close();
|
||||
} catch (IOException ignored) {}
|
||||
Logger.info("HTTP", "Connection closed gracefully");
|
||||
} catch (IOException e) {
|
||||
Logger.error("HTTP", "Error closing socket: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
running = false;
|
||||
if (serverSocket != null) {
|
||||
|
||||
@@ -4,9 +4,8 @@ import org.lumijiez.core.http.HttpHandler;
|
||||
import org.lumijiez.core.http.HttpRequest;
|
||||
import org.lumijiez.core.http.HttpResponse;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Router {
|
||||
@@ -17,7 +16,7 @@ public class Router {
|
||||
routes.put(key, handler);
|
||||
}
|
||||
|
||||
public void handleRequest(HttpRequest request, HttpResponse response) {
|
||||
public void handleRequest(HttpRequest request, HttpResponse response) throws IOException {
|
||||
String key = request.getMethod().toUpperCase() + ":" + request.getPath();
|
||||
HttpHandler handler = routes.get(key);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user