support for keep-alive and close connections
This commit is contained in:
@@ -1,6 +1,8 @@
|
|||||||
package org.lumijiez.core.http;
|
package org.lumijiez.core.http;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
@FunctionalInterface
|
@FunctionalInterface
|
||||||
public interface HttpHandler {
|
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;
|
package org.lumijiez.core.http;
|
||||||
|
|
||||||
import org.lumijiez.logging.Logger;
|
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
public class HttpRequest {
|
public class HttpRequest {
|
||||||
private String method;
|
private String method;
|
||||||
private String path;
|
private String path;
|
||||||
private String httpVersion;
|
private String httpVersion;
|
||||||
|
private final Map<String, String> headers;
|
||||||
|
|
||||||
public HttpRequest(BufferedReader in) throws IOException {
|
public HttpRequest(BufferedReader in) throws IOException {
|
||||||
|
this.headers = new HashMap<>();
|
||||||
parseRequest(in);
|
parseRequest(in);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void parseRequest(BufferedReader in) throws IOException {
|
private void parseRequest(BufferedReader in) throws IOException {
|
||||||
String requestLine;
|
String requestLine = in.readLine();
|
||||||
|
if (requestLine != null && !requestLine.trim().isEmpty()) {
|
||||||
while ((requestLine = in.readLine()) != null) {
|
String[] tokens = requestLine.split(" ");
|
||||||
|
if (tokens.length == 3) {
|
||||||
if (!requestLine.trim().isEmpty()) {
|
this.method = tokens[0];
|
||||||
String[] tokens = requestLine.split(" ");
|
this.path = tokens[1];
|
||||||
if (tokens.length == 3) {
|
this.httpVersion = tokens[2];
|
||||||
this.method = tokens[0];
|
} else {
|
||||||
this.path = tokens[1];
|
throw new IOException("Invalid request line format.");
|
||||||
this.httpVersion = tokens[2];
|
|
||||||
break;
|
|
||||||
} else {
|
|
||||||
Logger.error("HTTP", "Invalid line format: " + requestLine);
|
|
||||||
throw new IOException("Invalid request line format.");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// String headerLine;
|
String headerLine;
|
||||||
// while ((headerLine = in.readLine()) != null && !headerLine.trim().isEmpty()) {
|
while ((headerLine = in.readLine()) != null && !headerLine.trim().isEmpty()) {
|
||||||
// Logger.info("HTTP-DEBUG", "Header: " + headerLine);
|
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() {
|
public String getMethod() {
|
||||||
|
|||||||
@@ -2,22 +2,44 @@ package org.lumijiez.core.http;
|
|||||||
|
|
||||||
import org.lumijiez.logging.Logger;
|
import org.lumijiez.logging.Logger;
|
||||||
|
|
||||||
import java.io.PrintWriter;
|
import java.io.BufferedWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
public class HttpResponse {
|
public class HttpResponse {
|
||||||
private final PrintWriter out;
|
private final BufferedWriter out;
|
||||||
|
|
||||||
public HttpResponse(PrintWriter out) {
|
public HttpResponse(BufferedWriter out) {
|
||||||
this.out = 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);
|
Logger.info("HTTP", "Outgoing: " + statusCode + " " + message);
|
||||||
out.println("HTTP/1.1 " + statusCode + " " + message);
|
|
||||||
out.println("Content-Type: text/plain");
|
out.write("HTTP/1.1 " + statusCode + " " + getStatusText(statusCode));
|
||||||
out.println("Connection: close");
|
out.write("\r\n");
|
||||||
out.println();
|
|
||||||
out.println(message);
|
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();
|
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.core.routing.Router;
|
||||||
import org.lumijiez.logging.Logger;
|
import org.lumijiez.logging.Logger;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.*;
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.io.PrintWriter;
|
|
||||||
import java.net.ServerSocket;
|
import java.net.ServerSocket;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
@@ -19,6 +17,10 @@ public class HttpServer {
|
|||||||
private final ExecutorService threadPool;
|
private final ExecutorService threadPool;
|
||||||
private final Router router;
|
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) {
|
public HttpServer(int port) {
|
||||||
this.running = false;
|
this.running = false;
|
||||||
this.port = port;
|
this.port = port;
|
||||||
@@ -63,39 +65,75 @@ public class HttpServer {
|
|||||||
|
|
||||||
protected void handleClient(Socket clientSocket) {
|
protected void handleClient(Socket clientSocket) {
|
||||||
try {
|
try {
|
||||||
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
clientSocket.setSoTimeout(KEEP_ALIVE_TIMEOUT);
|
||||||
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
|
|
||||||
|
|
||||||
in.mark(32000);
|
BufferedReader in = new BufferedReader(
|
||||||
if (!in.ready()) {
|
new InputStreamReader(clientSocket.getInputStream()),
|
||||||
clientSocket.close();
|
BUFFER_SIZE
|
||||||
return;
|
);
|
||||||
|
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) {
|
} catch (IOException e) {
|
||||||
Logger.error("HTTP", "Error handling client: " + e.getMessage());
|
if (running) {
|
||||||
|
Logger.error("HTTP", "Error handling client: " + e.getMessage());
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
try {
|
try {
|
||||||
clientSocket.close();
|
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() {
|
public void stop() {
|
||||||
running = false;
|
running = false;
|
||||||
if (serverSocket != null) {
|
if (serverSocket != null) {
|
||||||
|
|||||||
@@ -4,9 +4,8 @@ import org.lumijiez.core.http.HttpHandler;
|
|||||||
import org.lumijiez.core.http.HttpRequest;
|
import org.lumijiez.core.http.HttpRequest;
|
||||||
import org.lumijiez.core.http.HttpResponse;
|
import org.lumijiez.core.http.HttpResponse;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.io.IOException;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public class Router {
|
public class Router {
|
||||||
@@ -17,7 +16,7 @@ public class Router {
|
|||||||
routes.put(key, handler);
|
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();
|
String key = request.getMethod().toUpperCase() + ":" + request.getPath();
|
||||||
HttpHandler handler = routes.get(key);
|
HttpHandler handler = routes.get(key);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user