I create javafx application and have to combine it with ServerSocket, but when I use function accept of ServerSocket the application is black out. what I expected is to let the application wait until there a Socket connect and run the next method. I have no idea what happen but when I comment the line of ServerSocket.accept() out it work just fine. I have try to read api doc of ServerSocket but I found no help in it or maybe I just too dull for it.
Main
package test;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.net.ServerSocket;
public class ProblemTest extends Application {
public static void main(String[] args) throws Exception{
launch(args);
}
public void start(Stage primaryStage)throws Exception{
FXMLLoader loader = new FXMLLoader(getClass().getResource("test.fxml"));
Parent root= loader.load();
Scene scene=new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
ServerSocket server=new ServerSocket(8000);
server.accept();
}
}
Fxml file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.VBox?>
<VBox prefHeight="400.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
<children>
<MenuBar>
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Clear" />
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
</menus>
</MenuBar>
<TextArea prefHeight="377.0" prefWidth="640.0" />
</children>
</VBox>
```
server.accept()
blocks application thread, you need to invoke accept()
in another thread.
new Thread(() -> {
... new ServerSocket(8000).accept();
}).start()