我正在开发一个Quiz游戏,带有一个Web服务器和一个客户端。现在,当客户端连接到服务器时,它崩溃了。原因是需要很长时间才能运行的代码应该在后台线程上执行,而不是在FX Application Thread上执行。这意味着我必须:
但是当我处理来自服务器的输入的可运行方法时,我该如何做呢?我正在尝试实施您可以在Using threads to make database requests
找到的教程当我来到这部分代码时会出现问题:
Task<Runnable> clientTask = new Task<Runnable>() {
@Override
public Client call() throws Exception {
return (Client) clientRunner;
}
};
clientTask.setOnSucceeded(e ->
Runnable clientRunner = clientTask.getValue(); //Cannot resolve symbol 'setOnsucceded'
executor.execute(clientTask); //Cannot resolve symbol 'executor' and unknow class clientTask
};
}
客户类:
package sample;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl.ThreadStateMap.Byte0.runnable;
public class Client implements Runnable {
@FXML
private TextArea Out = new TextArea();
@FXML
private TextField Input = new TextField();
String alias;
String ServerAddress = "localhost";
String userAnswer;
BufferedReader reader;
PrintWriter writer;
@FXML
public void initialize() {
bQuit.setOnAction(event -> Platform.exit());
aliasField.setOnAction(a -> {
alias = aliasField.getText();
Input.setOnAction(b -> {
userAnswer = Input.getText();
});
});
aliasField.setPromptText("Alias");
Input.setPromptText("And your answer is:");
IP.setPromptText("IP to the server");
ExecutorService executor = Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t;
});
}
Runnable clientRunner = new Runnable() {
@Override
public void run() {
try {
Socket clientSocket = new Socket(ServerAddress, 9001);
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
writer = new PrintWriter(clientSocket.getOutputStream(), true);
Scanner newObject = new Scanner(reader);
while (newObject.hasNextLine())
Out.appendText(newObject.next() + "");
} catch (IOException e) {
System.out.println("Something isn't working as intended =(");
}
}
Task < Runnable > clientTask = new Task < Runnable > () {
@Override
public Client call() throws Exception {
return (Client) clientRunner;
}
};
clientTask.setOnSucceeded(e ->
Runnable clientRunner = clientTask.getValue(); //Cannot resolve symbol 'setOnsucceded'
executor.execute(clientTask); //Cannot resolve symbol 'executor' and unknow class clientTask
};
}