等待连接时,服务器GUI冻结

时间:2017-12-08 16:50:32

标签: java multithreading

我试图创建一个多线程服务器,通过客户端连接到它可以正常工作,但GUI被冻结了。可能因为它一直在监听传入的连接,所以它会在一个while循环中停留。那么,我是否需要为多线程服务器(它本身将创建线程)创建一个线程,或者我将如何解决此问题呢?

MultiThreadedServer:

public class MultiThreadServer{

    public static final int PORT = 2000;
    //function below is called by the GUI. 
    public void startServer() throws IOException {
        ServerSocket s = new ServerSocket(PORT);
        System.out.println("Server socket: " + s);
        System.out.println("Server listening...");
        try { while(true) {
            // Blocks until a connection occurs:
            Socket socket = s.accept();
            System.out.println("Connection accepted.");
            System.out.println("The new socket: " + socket);
            try {
                ClientThread t = new ClientThread(socket);
                System.out.println("New thread started.");
                System.out.println("The new thread: " + t);

                }
                catch(IOException e) {
                    System.out.println("===Socket Closed===");
                    socket.close();
                }
            } 
        } 
        finally { System.out.println("===ServerSocket Closed==="); s.close(); }
        } 
    } 
}

ServerGUI:

public class ServerGUI extends Application implements Initializable{

    @FXML private MenuItem startConn;

    @Override
    public void start(Stage stage) throws Exception {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("ServerGUI.fxml"));
            stage.setScene(new Scene(root));
            stage.show();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void initialize(URL location, ResourceBundle resources) {

        startConn.setOnAction(e -> {
            try {
                MultiThreadServer mts = new MultiThreadServer();
                mts.startServer();
                System.out.println("Starting Server...");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

正如我所怀疑的,需要一个服务器的新线程。

<强> MultiThreadServer:

public Runnable startServer() throws IOException {

在完成函数Runnable后,我添加了这个:

ServerGUI:

startConn.setOnAction(e -> {
            Thread t1 = new Thread(new Runnable() {
                public void run()
                {
                    MultiThreadServer mts = new MultiThreadServer();

                    try {
                        mts.startServer();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }});  
                t1.start();

感谢用户 BackSlash 提供参考链接。