-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleHTTPServer.java
More file actions
36 lines (31 loc) · 1.45 KB
/
SimpleHTTPServer.java
File metadata and controls
36 lines (31 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Date;
public class SimpleHTTPServer {
public static void main(String[] args) throws Exception {
// Create a server object that listens for incoming connections on port 8080.
final ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080...");
// Infinite loop because we don't want the server to open and close.
while (true) {
// Create a Socket object which represents the connection and is used to read incoming HTTP request and send HTTP response.
try(Socket clientSocket = server.accept()) {
// Read the incoming HTTP request
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
// Read the first line of the request
String line = reader.readLine();
// Print all the lines of the request
while (!line.isEmpty()) {
System.out.println(line);
line = reader.readLine();
}
Date today = new Date(0);
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
clientSocket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
}
}
}
}