Implement http server

This commit is contained in:
2025-12-03 15:58:39 +01:00
parent 02da98dff5
commit 223b3c4fdf
3 changed files with 100 additions and 6 deletions

View File

@@ -0,0 +1,33 @@
package common.common.src.html;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class HtmlManager {
public String serveFile(String path){
String content = readFile(path);
return "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + content.length() + "\r\n" +
"\r\n" +
content;
}
private String readFile(String path){
File file = new File(path);
try(BufferedReader fileReader = new BufferedReader(new FileReader(file))){
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = fileReader.readLine()) != null) {
responseBody.append(line);
}
return responseBody.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -1,18 +1,34 @@
package httpsServer.httpServer.src;
import common.common.src.html.HtmlManager;
import common.common.src.socket.SocketManager;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) {
final HtmlManager htmlManager = new HtmlManager();
int port = 8043;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server started on port " + port);
final InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8043);
while (true) {
try (Socket clientSocket = serverSocket.accept()) {
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
try(Socket socket = new Socket()){
socket.bind(address);
} catch (Exception e){
String requestLine = in.readLine();
System.out.println("Request: " + requestLine);
String response = htmlManager.serveFile("./assets/pages/index.html");
SocketManager.send(clientSocket, response);
} catch (IOException e) {
System.err.println("Client connection error: " + e.getMessage());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}