我正在尝试使用简单的GUI设置服务器,当客户端建立连接并进行标准操作时,我将在其中进行打印。当我尝试执行它时会发生问题,因为GUI无法启动(即使NetBeans说程序已执行),我也不明白线程之间是否存在某种冲突,或者我是否在其中调用了它。一种机翼方式。这是程序启动的代码:
public class Server extends Application {
@Override
public void start(Stage stage) throws Exception {
FXMLLoader sLoader = new FXMLLoader(getClass().getResource("server.fxml"));
BorderPane root = new BorderPane(sLoader.load());
ServerController sController = sLoader.getController();
sController.initModel();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
这是服务器的控制器,我在这里放在init函数中,即Socket等待客户端的部分:
public class ServerController {
@FXML
private TextArea textarea;
public void initModel() {
try {
int i = 1;
ServerSocket s = new ServerSocket(5000);
while (true) {
Socket incoming = s.accept(); // si mette in attesa di richiesta di connessione e la apre
textarea.setText("In attesa di connessioni...");
Runnable r = new ThreadedEchoHandler(incoming, i);
new Thread(r).start();
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
class ThreadedEchoHandler implements Runnable {
private Socket incoming;
private int counter;
/**
* Constructs a handler.
*
* @param i the incoming socket
* @param c the counter for the handlers (used in prompts)
*/
public ThreadedEchoHandler(Socket in, int c) {
incoming = in;
counter = c;
}
//Con questo gestisco le stringhe
public void run() {
try {
try {
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
Scanner in = new Scanner(inStream);
PrintWriter out = new PrintWriter(outStream, true);
//out.println("Hello! Enter BYE to exit.");
// echo client input
boolean done = false;
while (!done && in.hasNextLine()) {
String line = in.nextLine();
//out.println("Echo: " + line);
//System.out.println("ECHO: " + line);
if (line.trim().equals("BYE")) {
done = true;
}
}
} finally {
incoming.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}