I need to make a client queue with ThreadPoolExecutor and an ability to drop clients if it exceeds some number (5 for example). It is kinda DDOS protection. When client #6 is requesting my server - it got dropped, etc. I got my server and client code, but I don't know how to realize ThreadPoolExecutor and DiscardPolicy. Ideas or examples?
Simple server:
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
ServerSocket server = new ServerSocket (3000);
ExecutorService es = Executors.newFixedThreadPool(2);
Semaphore semaphore = new Semaphore (2);
while(true){
semaphore.acquire();
Socket accept2 = server.accept();
es.execute(()->{
try (Socket accept = accept2) {
serve(accept);
} catch (Exception exception) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, exception);
}
finally {
semaphore.release();
}
});
}
}
private static void serve(final Socket accept) throws ClassNotFoundException, IOException {
InputStream inputStream = accept.getInputStream();
OutputStream outputStream = accept.getOutputStream();
ObjectInputStream inputStream2 = new ObjectInputStream (inputStream);
while (true){
Object readObject = inputStream2.readObject();
System.out.println(readObject);
}
}
}
And a simple client:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
Socket socket = new Socket ("localhost", 3000);
ObjectOutputStream oos = new ObjectOutputStream (
socket.getOutputStream());
oos.writeObject("First!");
Thread.sleep(10000);
oos.writeObject("First again!");
Thread.sleep(10000);
oos.writeObject("First again again!");
}
}