我已经尝试解决这个问题有一段时间了,
我正在尝试编写一个聊天服务器应用程序,仅供学习。 我有一个我无法理解的障碍,
GUI 类内部的 while 循环卡住,但就在它尝试读取时:
public void run(){
Platform.runLater(() -> {
do {
try {
msg = getFromServer.readUTF(); // <--- freeze GUI
chatWindow.appendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
} while (true);
});
}
你可以看到它在一个线程中运行,但我确实尝试以其他方式运行它......
只有 DataInputStream 才会卡住,
msg = getFromServer.readUTF();
这就是它的来源:
public void connectToServer(){
try {
serverConectionState = new Socket("127.0.0.1", 6789);
getFromServer = new DataInputStream(serverConectionState.getInputStream());
sendToServer = new DataOutputStream(serverConectionState.getOutputStream());
onlineOffline.setText("Online");
onlineOffline.setTextFill(javafx.scene.paint.Color.web("#0076a3"));
} catch (IOException ex){
chatWindow.appendText("server connection fail\n");
}
}
这个类是 Controller.class - 如果它有任何不同。
在社区提供了大量帮助后,我在 stackoverflow 中遇到的第一个问题。
提前致谢
最佳答案
我假设您展示的 run
方法是在后台线程中执行的 Runnable
的一部分。
您正在 FX 应用程序线程上运行整个循环(通过使用 Platform.runLater()
)。因此,您可以阻止该线程并防止其重新绘制。您应该仅在 FX 应用程序线程上运行 UI 更新:
public void run(){
do {
try {
String msg = getFromServer.readUTF(); // <--- freeze GUI
Platform.runLater(() -> chatWindow.appendText(msg));
} catch (IOException e) {
e.printStackTrace();
}
} while (true);
}
关于当 DataInputStream 处于 while 循环中时 JavaFX GUI 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35363197/