Main File
public class Main {
private static final String CONTEXT = "/app";
private static final int PORT = 5000;
public static void main(String[] args) throws Exception {
// Create a new SimpleHttpServer
Server simpleHttpServer = new Server(PORT, CONTEXT,
new Request());
// Start the server
simpleHttpServer.start();
System.out.println("Server is started and listening on port "+ PORT);
}
}
Server.java
import java.io.IOException;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server {
private HttpServer httpServer;
public Server(int port, String context, HttpHandler handler) {
try {
//Create HttpServer which is listening on the given port
httpServer = HttpServer.create(new InetSocketAddress(port), 0);
//Create a new context for the given context and handler
httpServer.createContext(context, handler);
//Create a default executor
httpServer.setExecutor(null);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
this.httpServer.start();
}
}
Request.java
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.concurrent.atomic.AtomicInteger;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.Filter;
public class Request implements HttpHandler {
private static final int HTTP_OK_STATUS = 200;
AtomicInteger atomicInteger = new AtomicInteger(0);
public void handle(HttpExchange t) throws IOException {
int theValue = atomicInteger.get();
String html = String.format("<html>\n" +
" <head>\n" +
" <title>Java Server</title>\n" +
" </head>\n" +
" <body>\n" +
" <p>Visitors\n <b><h1>%d</h1></b></p>\n" +
" </body>\n" +
"</html>",theValue);
System.out.println("os: " + html);
atomicInteger.addAndGet(1);
t.sendResponseHeaders(HTTP_OK_STATUS, html.getBytes().length);
//Write the response string
OutputStream os = t.getResponseBody();
System.out.println("os: " + html);
os.write(html.getBytes());
os.close();
}
}
I created a simple http server with java. I set the server to run only in the app directory and port 5000, and it only needs to respond to get requests. I have to identify unique users coming to the server I want and print it in html. I'm suppressing the number of visitors to the server, but I don't know how to filter for unique. How can I filter?