/
on-line-javalex
/
HW_FORMS
Обзор
Документация
Войти
/
on-line-javalex
/
HW_FORMS
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Server.java
94 строки
3 KB
on-line-javalex
upload files
03 мар 2026, 07:47
Верифицирован
03 мар 2026, 07:47
468c7a8
Код
Авторство
О чём код?
package netology; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Server { private final int port; private final ExecutorService threadPool; private final Map<String, Handler> handlers = new ConcurrentHashMap<>(); private static final int THREAD_POOL_SIZE = 64; private static final String PUBLIC_DIR = "./public"; public Server(int port) { this.port = port; this.threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE); } public void addHandler(String method, String path, Handler handler) { handlers.put(method + ":" + path, handler); } public void start() { try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server started on port " + port); while (true) { Socket socket = serverSocket.accept(); threadPool.submit(() -> handleConnection(socket)); } } catch (IOException e) { e.printStackTrace(); } finally { threadPool.shutdown(); } } private void handleConnection(Socket socket) { try (Socket s = socket; InputStream in = s.getInputStream(); BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream())) { HttpRequest request = HttpRequest.fromInputStream(in); String key = request.getMethod() + ":" + request.getPath(); Handler handler = handlers.get(key); if (handler != null) { handler.handle(request, out); } else { serveStaticFile(request.getPath(), out); } out.flush(); } catch (Exception e) { e.printStackTrace(); } } private void serveStaticFile(String path, BufferedOutputStream out) throws IOException { Path filePath = Paths.get(PUBLIC_DIR, path).normalize(); if (!filePath.startsWith(Paths.get(PUBLIC_DIR).normalize()) || !Files.exists(filePath) || Files.isDirectory(filePath)) { sendNotFound(out); return; } String mimeType = Files.probeContentType(filePath); if (mimeType == null) { mimeType = "application/octet-stream"; } byte[] content = Files.readAllBytes(filePath); String header = "HTTP/1.1 200 OK\r\n" + "Content-Type: " + mimeType + "\r\n" + "Content-Length: " + content.length + "\r\n" + "Connection: close\r\n" + "\r\n"; out.write(header.getBytes()); out.write(content); } private void sendNotFound(BufferedOutputStream out) throws IOException { String response = "HTTP/1.1 404 Not Found\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"; out.write(response.getBytes()); } }