我需要做一个客户端队列的ThreadPoolExecutor和下降的客户的能力,如果超过一定数目(例如5)。 它是有点儿DDOS防护。 当客户端#6请求我的服务器 - 它得到了下降,等我有我的服务器和客户端的代码,但我不知道如何实现的ThreadPoolExecutor和DiscardPolicy。 想法或例子?
简单的服务器:
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);
}
}
}
而一个简单的客户端:
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!");
}
}