import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class TimeServer {
static class GetHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
var calendar = Calendar.getInstance();
var dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss\n");
byte[] response = dateFormat.format(calendar.getTime()).getBytes();
// Set the response header and status code
exchange.sendResponseHeaders(200, response.length);
// Get the response body output stream
OutputStream responseBody = exchange.getResponseBody();
System.out.print(exchange.getRemoteAddress());
responseBody.write(response);
responseBody.close();
}
}
public static void main(String[] args) throws Exception {
// Create a server on port 8000
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", new GetHandler()); // "GET /" handler
server.start(); // Start serving requests
}
}