Last active
December 27, 2021 12:50
-
-
Save ahndmal/6da91946ebe2ac75a8ae2e55cddba020 to your computer and use it in GitHub Desktop.
java-web-server-with-socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package test | |
| import java.io.BufferedReader; | |
| import java.io.IOException; | |
| import java.io.InputStreamReader; | |
| import java.io.PrintWriter; | |
| import java.net.ServerSocket; | |
| import java.net.Socket; | |
| import java.nio.charset.StandardCharsets; | |
| import java.nio.file.Files; | |
| import java.nio.file.Path; | |
| import java.nio.file.Paths; | |
| public class WebServer { | |
| private static String WWW = "/Users/macbook/IdeaProjects/first-geek-web-server/www"; | |
| public static void main(String[] args) { | |
| try (ServerSocket serverSocket = new ServerSocket(8080)) { | |
| System.out.println("Server started!"); | |
| while (true) { | |
| Socket socket = serverSocket.accept(); | |
| System.out.println("New client connected!"); | |
| new Thread(() -> handleRequest(socket)).start(); | |
| } | |
| } catch (IOException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| private static void handleRequest(Socket socket) { | |
| try (BufferedReader input = new BufferedReader( | |
| new InputStreamReader( | |
| socket.getInputStream(), StandardCharsets.UTF_8)); | |
| PrintWriter output = new PrintWriter(socket.getOutputStream()) | |
| ) { | |
| while (!input.ready()); | |
| String firstLine = input.readLine(); | |
| String[] parts = firstLine.split(" "); | |
| System.out.println(firstLine); | |
| while (input.ready()) { | |
| System.out.println(input.readLine()); | |
| } | |
| Path path = Paths.get(WWW, parts[1]); | |
| if (!Files.exists(path)) { | |
| output.println("HTTP/1.1 404 NOT_FOUND"); | |
| output.println("Content-Type: text/html; charset=utf-8"); | |
| output.println(); | |
| output.println("<h1>Файл не найден!</h1>"); | |
| output.flush(); | |
| return; | |
| } | |
| output.println("HTTP/1.1 200 OK"); | |
| output.println("Content-Type: text/html; charset=utf-8"); | |
| output.println(); | |
| Files.newBufferedReader(path).transferTo(output); | |
| System.out.println("Client disconnected!"); | |
| } catch (IOException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment