我有一个Java服务器,它监听来自PHP客户端的连接并回复。我的问题是我在读取inputStream后无法向outputStream写任何内容。
while (true)
try {
clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(2000);
if (!clientSocket.getInetAddress().equals(clientSocket.getLocalAddress())) {
clientSocket.close();
continue;
}
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
LinkedList<String> messageFromPHP = new LinkedList<>();
String message = "";
while ((message = br.readLine()) != null)
messageFromPHP.add(message);
bw.write("test_message\n");
bw.flush();
bw.close();
br.close();
clientSocket.close();
} catch (SocketTimeoutException ex) {
} catch (IOException ex) {
ex.printStackTrace();
serverSocket.close();
}
^^这使得PHP客户端和Java Server都永远停滞不前。 (我已将SoTimeout添加到服务器以防止这种情况发生)
while (true)
try {
clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(2000);
if (!clientSocket.getInetAddress().equals(clientSocket.getLocalAddress())) {
clientSocket.close();
continue;
}
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
LinkedList<String> messageFromPHP = new LinkedList<>();
String message = "";
while ((message = br.readLine()) != null) {
messageFromPHP.add(message);
bw.write("test_message\n");
bw.flush();
}
bw.close();
br.close();
clientSocket.close();
} catch (SocketTimeoutException ex) {
} catch (IOException ex) {
ex.printStackTrace();
serverSocket.close();
}
^^然而,这个工作完全正常,我不知道为什么。我确定这些while循环结束是因为我可以打印messageFromPHP而没有两个代码的问题。
那么,我怎样才能避免在readLine循环中做所有事情?
编辑:更清楚:我想像第一个代码一样编写和阅读。但是当我读取输入时,我无法写入输出,所以我必须使用第二个代码而我不想这样做。我正在尝试将输入存储在messageFromPHP列表中,然后根据列表中的输入写入输出。