在JavaFX应用程序中保持ServerSocket处于活动状态

时间:2018-10-03 12:39:53

标签: java javafx java-8 javafx-8

我有两个JavaFX应用程序,一个扮演 client 角色,我可以从中将消息发送到代表服务器的另一个应用程序中我使用SocketServerSocket进行实施,现在我可以从客户端发送一条消息,并且在服务器端已成功接收到该消息,此后连接将被关闭,那么如何保持它的活动状态并发送多条消息?

Client.java

public class Client extends Application {
    @Override
    public void start(Stage primaryStage) {
        Label connLabel = new Label("Not connected");
        TextArea message = new TextArea();
        message.setPromptText("Type your message here ...");
        Button btn = new Button();
        btn.setText("Send");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                try {
                    Socket c = new Socket("127.0.0.1", 2004);
                    connLabel.setText("connected");
                    ObjectOutputStream out = new ObjectOutputStream(c.getOutputStream());
                    out.writeObject(message.getText());
                    c.close();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        VBox root = new VBox();
        root.setSpacing(10);
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(25));
        root.getChildren().addAll(message, btn);
        Scene scene = new Scene(root, 600, 600);
        primaryStage.setTitle("Client");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }

}

Server.java

public class Server extends Application {
    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox();
        Label msgRecu = new Label();
        root.setSpacing(10);
        root.setPadding(new Insets(25));
        root.setAlignment(Pos.CENTER);
        root.getChildren().addAll(msgRecu);
        Scene scene = new Scene(root, 600, 600);
        try {
            ServerSocket s = new ServerSocket(2004);
            System.out.println("Waiting");
            Socket connection;
            String ch = null;
            connection = s.accept();
            System.out.println("Accepted");
            ObjectInputStream in = new ObjectInputStream(connection.getInputStream());
            ch = (String) in.readObject();
            msgRecu.setText(ch);
            primaryStage.setTitle("Server");
            primaryStage.setScene(scene);
            primaryStage.show();
            s.close();
            connection.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static void main(String[] args) {
        launch(args);
    }

}

0 个答案:

没有答案