2017-02-13 4 views
0

안녕하세요, 서버를 구현하는 중입니다. 문제는 서버가 inputstream에서 메시지를받지 못하고 기다릴 때까지 기다리는 것입니다. 클라이언트가 스트림에 기록한 후에 스트림을 닫지 않으면 서버는 계속 대기합니다. 클라이언트는 메시지를 보낸 후 응답을 기다리는 inputstream에서 읽으려고하지만 서버가 요청을 기다리고 있습니다. 그래서 ..이 내 클라이언트 클래스자바 소켓 통신 "교착 상태"

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(); 
     } 
    } 
} 

}

입니다

교착 그리고이 각 클라이언트

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("-"); 
       ... 
처리를위한 내 서버 클래스

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를 클래스

누구든지이 문제를 해결하도록 도와 줄 수 있습니까?

답변

2
pw.write(request); 

클라이언트가 요청을 작성했지만 회선이 아닙니다. 서버가 readLine()과 함께 회선을 읽었으며 회선 종결자가 도착할 때까지 차단되어 회신을 보내지 않으므로 클라이언트는 절대로 회람을받지 못하므로 영원히 차단됩니다. 에

변경에게 위 :

pw.println(request); 
+0

대단히 감사합니다! 감사합니다 –