0
嗨我想實現與乘客客戶端運行的服務器 問題是,服務器沒有收到來自inputstream的消息,並等待它發生。如果客戶端在寫入數據流後沒有關閉流,服務器將繼續等待。客戶端發送消息後,他嘗試從輸入流中讀取等待響應,但服務器正在等待請求。所以..死鎖Java Socket通信「死鎖」
這是我的客戶端類
public class Client implements Runnable{
...
@Override
public void run() {
BufferedReader is = null;
BufferedWriter os = null;
try(Socket socket = new Socket(address.getHostName(), address.getPort());){
String request = String.format("%s-%d-%s",this.destination, this.desiredPlace, this.paymentMethod.toString());
os = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(os, true);
pw.write(request);
pw.flush();
// if I close the stream here the request will be send, but this will close the socket so the I will not receive response.
String response;
while ((response = is.readLine()) != null){
System.out.println(response);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
這是我的服務器類
public void perform() throws IOException, DestionationProcessingException, InterruptedException {
try (ServerSocket server = new ServerSocket(port);) {
StandalonePayDesk offLinePayDesk = new StandalonePayDesk(ticketManager);
this.threadPool.submit(offLinePayDesk);
while (true) {
Socket socket = server.accept();
RequestHandler handler = new RequestHandler(this.threadPool, offLinePayDesk, this.ticketManager);
handler.process(socket);
}
}
}
和RequestHandler類來處理每個客戶
try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter writer = new PrintWriter(client.getOutputStream(), true)) {
writer.println("hello");
writer.flush();
String line;
while ((line = reader.readLine()) != null) {
String[] lineTokens = line.split("-");
...
任何人都可以幫我解決這個問題嗎?
非常感謝您!我很感激 –