2017-04-06 5 views
2

내 서버에서 클라이언트 측 Textarea에 문자열을 추가하려고합니다 (채팅 창 사용). 문제는 문자열을 받으면 클라이언트가 멈 춥니 다.TextArea에 텍스트를 추가 할 때 발생하는 문제 (JavaFX 8)

insertUserNameButton.setOnAction((event) -> { 
     userName=userNameField.getText(); 
     try { 
      connect(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    }); 

public Client() { 
    userInput.setOnAction((event) -> { 

     out.println(userInput.getText()); 
     userInput.setText(""); 

    }); 
} 

private void connect() throws IOException { 

    String serverAddress = hostName; 
    Socket socket = new Socket(serverAddress, portNumber); 
    in = new BufferedReader(new InputStreamReader(
      socket.getInputStream())); 
    out = new PrintWriter(socket.getOutputStream(), true); 

    while (true) { 
      String line = in.readLine(); 

     if (line.startsWith("SUBMITNAME")) { 
      out.println(userName); 

     } else if (line.startsWith("MESSAGE")) { 
      Platform.runLater(()->serverOutput.appendText(line.substring(8) + "\n")); 

     } else if (line.startsWith("QUESTION")) { 
      Platform.runLater(()->serverOutput.appendText(line.substring(8) + "\n")); 

     } else if (line.startsWith("CORRECTANSWER")) { 
      Platform.runLater(()->serverOutput.appendText(line.substring(14) + "\n")); 
     } 
    } 
} 

public static void main(String[] args) { 
    launch(args); 
} 

나는 약간의 조사를했으며, 각 추가시 Platform.runLater를 사용하면 문제가 해결 될 것으로 보인다. 그것은 나를위한 것이 아닙니다.

누구나 그것이 원인이 될 수있는 아이디어가 있습니까? 고맙습니다!

+0

는'()'를 연결하려면 다음

private final Executor exec = Executors.newCachedThreadPool(runnable -> { Thread t = new Thread(runnable); t.setDaemon(true); return t ; }); 

과 :이 스레드를 관리하는 Executor을 사용하는 것이 가장 좋습니다? 어떤 스레드에서? –

+0

코드를 편집했습니다. 액션 이벤트에서 호출되었습니다. 연결을 시작하는 연결 단추. 스레드가 없습니다. – binerkin

+0

이벤트 처리기에서 호출하는 경우 FX 응용 프로그램 스레드에서 실행 중입니다. 그래서 무한한 while (true) {...} 루프가 FX 응용 프로그램 스레드에서 실행 중이며이를 차단하고 UI가 업데이트를 수행하지 못하도록합니다. 이것을 백그라운드 스레드에서 실행해야합니다. –

답변

2

FX 응용 프로그램 스레드에서 connect() (으)로 전화하고 있습니다.

while(true) { 
    String line = in.readLine(); 
    // ... 
} 

구조를 통해 무기한 차단하기 때문에, 당신은 FX 응용 프로그램 스레드를 차단하고 (등, 사용자 이벤트에 응답 UI를 렌더링) 평소 작업 중 하나를 수행 않도록.

배경 스레드에서 실행해야합니다. 당신이 호출

insertUserNameButton.setOnAction((event) -> { 
    userName=userNameField.getText(); 
    exec.execute(() -> { 
     try { 
      connect(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    }); 
}); 
+0

그랬어! 고맙습니다! – binerkin