我试图使用执行程序服务来制作多线程服务器,并为每个连接提供一个新线程。我在以下代码中注意到的一个问题是,当我从PrintWriter
删除附加模式时,该操作停止工作,并且客户端与服务器之间没有通信。但是如果我添加
true
用于附加模式,事情开始起作用。
public class KnockKnockServer {
private ServerSocket server;
private ExecutorService threadPool;
public KnockKnockServer() {
try {
server = new ServerSocket(4444);
} catch (IOException e) {
e.printStackTrace();
}
threadPool = Executors.newCachedThreadPool();
}
public void processClients() {
try {
while(true) {
Socket acceptedConn = server.accept();
//Here if i remove true no communication
PrintWriter out = new PrintWriter(acceptedConn.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(acceptedConn.getInputStream()));
threadPool.execute(() -> {
try {
KnockKnockProtocol protocol = new KnockKnockProtocol();
String outputLine, inputLine;
outputLine = protocol.processInput(null);
out.println(outputLine);
while((inputLine = in.readLine()) != null) {
outputLine = protocol.processInput(inputLine);
out.println(outputLine);
if(outputLine.equals("Bye."))
break;
}
} catch(Exception e) {
e.printStackTrace();
}
});
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
server.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
}