Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.itstep;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.HashMap;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- try (ServerSocket server = new ServerSocket(9090)) {
- System.out.println("Сервер запущен");
- while (true) {
- try (
- Socket client = server.accept();
- Scanner input = new Scanner(client.getInputStream());
- PrintWriter output = new PrintWriter(client.getOutputStream())
- ) {
- System.out.println("Установлено соединение");
- String firstRow = input.nextLine();
- String row;
- HashMap<String, String> headers = new HashMap<>();
- do {
- row = input.nextLine();
- System.out.println(row);
- if (row.length() > 0) {
- String[] header = row.split(":");
- headers.put(
- header[0].toLowerCase(),
- header[1].trim()
- );
- }
- } while (row.length() > 0);
- if (firstRow.contains("POST")) {
- int length = Integer.parseInt(headers.get("content-length"));
- byte[] bytes = new byte[length];
- System.out.println(client.getInputStream().read(bytes, 0, length));
- System.out.println(new String(bytes));
- }
- String response = "Hello, AJAX!";
- output.println("HTTP/1.1 200 OK");
- output.println("Content-Type: text/html; charset=UTF-8");
- output.println("Content-Length: " + response.length());
- output.println("Access-Control-Allow-Origin: *");
- output.println();
- output.println(response);
- output.flush();
- System.out.println("Соединение разорвано");
- } catch (Throwable e) {
- e.printStackTrace();
- System.out.println("Ошибка соединения");
- }
- }
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement