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; public class HttpServer { 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("Client connected!"); // // try (BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter output = new PrintWriter(socket.getOutputStream(), StandardCharsets.UTF_8)) { // while (!input.ready()) ; // System.out.println(); while (input.ready()) { System.out.println(input.readLine()); } // output.println("HTTP/1.1 200 OK"); output.println("Content-Type: text/html; charset=utf-8"); output.println(); output.println("<p> !</p>"); output.flush(); // try-with-resources , // System.out.println("Client disconnected!"); } } } catch (IOException ex) { ex.printStackTrace(); } } }
http://localhost:8080/
in the address bar. If everything went well, then in the browser window we will see the text “Hello to all”, and in the server log there is a text similar to the one below: Server started! Client connected! GET / HTTP/1.1 Host: localhost:8080 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,he;q=0.6,de;q=0.5,cs;q=0.4 Cookie: _ga=GA1.1.1849608036.1549463927; portainer.pagination_containers=100; _gid=GA1.1.80775985.1550669456; If-Modified-Since: Sat, 05 Jan 2019 12:10:16 GMT Client disconnected!
http://localhost:8080/something
in your browser and see how the request text in the log changes.[ ] : []; []; ... []
[ ] : []; []; ... []
[ ] : []; []; ... []
.Source: https://habr.com/ru/post/441150/
All Articles