_ums_

Task

May 17th, 2022
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.03 KB | None | 0 0
  1. import java.io.RandomAccessFile;
  2. import java.net.InetSocketAddress;
  3. import java.nio.charset.Charset;
  4. import java.nio.charset.StandardCharsets;
  5. import java.util.Random;
  6.  
  7. public class Practicum {
  8.     private static final int PORT = 8080;
  9.     private static Random rnd = new Random();
  10.  
  11.     // IOException могут сгенерировать методы create() и bind(...)
  12.     public static void main(String[] args) throws IOException {
  13.         HttpServer httpServer = HttpServer.create();
  14.  
  15.         httpServer.bind(new InetSocketAddress(PORT), 0);
  16.         httpServer.createContext("/hello", new HelloHandler());
  17.         httpServer.createContext("/day", new MyHelloHandle());
  18.         httpServer.start(); // запускаем сервер
  19.  
  20.         System.out.println("HTTP-сервер запущен на " + PORT + " порту!");
  21.         httpServer.stop(1);
  22.     }
  23.  
  24.     static class HelloHandler implements HttpHandler {
  25.         @Override
  26.         public void handle(HttpExchange httpExchange) throws IOException {
  27.             System.out.println("Началась обработка /hello запроса от клиента.");
  28.  
  29.             String response = "Hey! Glad to see you on our server.";
  30.             httpExchange.sendResponseHeaders(200, 0);
  31.  
  32.             try (OutputStream os = httpExchange.getResponseBody()) {
  33.                 os.write(response.getBytes());
  34.             }
  35.         }
  36.     }
  37.  
  38.     static class MyHelloHandle implements HttpHandler {
  39.         @Override
  40.         public void handle(HttpExchange exchange) throws IOException {
  41.             System.out.println("Началась обработка /day запроса от клиента.");
  42.  
  43.             String[] days = new String[]{"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"};
  44.             int index = rnd.nextInt(7);
  45.             String response = days[index];
  46.             exchange.sendResponseHeaders(200, 0);
  47.  
  48.             try (OutputStream os = exchange.getResponseBody()) {
  49.                 os.write(response.getBytes());
  50.             }
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment