66 lines
2.1 KiB
Java
66 lines
2.1 KiB
Java
import java.io.BufferedReader;
|
|
import java.io.IOException;
|
|
import java.io.InputStreamReader;
|
|
import java.io.OutputStream;
|
|
import java.net.ServerSocket;
|
|
import java.net.Socket;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
public class Main {
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
try (ServerSocket serverSocket = new ServerSocket(8080)) {
|
|
System.out.println("listening on socket 8080...");
|
|
while (true) {
|
|
// .accept() blocks until we have a client
|
|
try (Socket client = serverSocket.accept()) {
|
|
handleClient(client);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public static void handleClient(Socket client) throws IOException {
|
|
|
|
System.out.println("Debug: got new client" + client.toString());
|
|
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
|
|
|
|
StringBuilder requestBuilder = new StringBuilder();
|
|
String line;
|
|
while (!(line = br.readLine()).isBlank()) {
|
|
requestBuilder.append(line + "\r\n");
|
|
}
|
|
String request = requestBuilder.toString();
|
|
// System.out.println(request);
|
|
String[] requestLines = request.split("\r\n");
|
|
String[] requestLine = requestLines[0].split(" ");
|
|
String method = requestLine[0];
|
|
String path = requestLine[1];
|
|
String version = requestLine[2];
|
|
String host = requestLines[1].split(" ")[1];
|
|
|
|
List<String> headers = new ArrayList<>();
|
|
// we start the loop from 2 because 0 is GET / HTTP/1.1 and 1 is the host
|
|
for (int h = 2; h < requestLines.length; h++) {
|
|
String header = requestLines[h];
|
|
headers.add(header);
|
|
}
|
|
|
|
String accessLog = String.format("Client %s, method %s, path %s, version %s, host %s, headers %s",
|
|
client.toString(),
|
|
method, path, version, host, headers.toString());
|
|
System.out.println(accessLog);
|
|
|
|
OutputStream clientOutput = client.getOutputStream();
|
|
clientOutput.write("HTTP/1.1 200 OK\r\n".getBytes());
|
|
clientOutput.write("ContentType: text/html\r\n".getBytes());
|
|
clientOutput.write("\r\n".getBytes());
|
|
clientOutput.write("<b>Hurray!!!1!</b>".getBytes());
|
|
clientOutput.write("\r\n\r\n".getBytes());
|
|
clientOutput.flush();
|
|
client.close();
|
|
}
|
|
|
|
}
|