所以我想要做的是有一个套接字,它接收来自客户端的输入,将客户端放入队列,然后当我的算法返回 true 时向队列中的每个客户端返回一条消息。
这个队列应该同时支持几百个客户端,但同时不会限制服务器,因此它实际上可以做它应该做的事情。
这是我到目前为止所拥有的:
private static final int PORT = 25566;
private static final int THREADS = 4;
private ExecutorService service;
public void init() throws IOException, IllegalStateException {
ServerSocket serverSocket;
serverSocket = new ServerSocket(PORT);
service = Executors.newCachedThreadPool();
Socket socket;
while(true) {
socket = serverSocket.accept();
System.out.println
("Connection established with " + socket.getInetAddress().toString());
service.execute(() -> {
Scanner scanner = null;
PrintWriter output = null;
String line = null;
try {
scanner = new Scanner(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream());
} catch(IOException e) {
e.printStackTrace();
}
try {
if (scanner == null || output == null)
throw new IllegalStateException("Scanner/PrintWriter is " + "null!");
line = scanner.nextLine();
while (line.compareTo("QUIT") != 0) {
/* This is where input comes in, queue for the algorithm,
algorithm happens then returns appropriate values */
output.flush();
line = scanner.nextLine();
}
} finally {
try {
System.out.println
("Closing connection with " + socket.getInetAddress().toString());
if(scanner != null) {
scanner.close();
}
if(output != null) {
output.close();
}
socket.close();
} catch(IOException e) {
e.printStackTrace();
}
}
});
}
}
现在我认为会发生这种情况,如果队列确实达到足够高的水平,我的线程池将完全成为服务器的瓶颈,因为所有线程都用于处理队列中的客户端,并且不会有足够的算法处理。
编辑:经过一堆测试,我认为如果在算法中它返回值然后断开连接,不等待用户响应而是在满足某些条件后让用户客户端重新连接,它会解决。