javafx应用程序和服务器套接字

6yjfywim  于 2021-08-20  发布在  Java
关注(0)|答案(0)|浏览(292)

因此,我正在创建一个在javafx应用程序上运行的出纳系统。还有一个客户机,每当客户离开订单时,它都会发送字符串消息。出纳服务器必须接收并分解我需要创建的部分 CarService 对象,然后更新 TableView 在服务器端的ui上显示该信息。问题是我的服务器运行得很好,ui也都完成了,但是当我想将它们结合在一起时,它们就不起作用了。
更具体地说,我知道服务器套接字与应用程序运行在不同的线程上,但我无法使它们一起工作。此外,插座必须保持打开状态,以便能够接收多个订单。我已经创建了运行应用程序的主类,我确实确定了服务器对象的初始化位置以及如何使用它,以便它首先生成、获取消息、将其分解为各个部分、创建 CarService 对象,然后通知对象并将其发送到 TableView 这样服务器端的用户就可以管理它。我为服务器端的ui提供代码。
服务器:

public class Server {

    public static ServerSocket serverSocket = null;
    public static Socket socket = null;
    public static boolean listening = true;

    public Server() throws IOException{
        try {
            serverSocket = new ServerSocket(7777);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Server initialized.");
        System.out.println("Server waiting...");

        while(listening){
            new EchoServerThread(serverSocket.accept()).start();
        }
    }
}

echoserverthread:

public class EchoServerThread extends Thread{

    private int sum;
    private String carID = "", carType = "", services = "", time = "";
    private CarService costumer;

    private Socket socket;

    public EchoServerThread(Socket socket){
        super("Server Thread");
        this.socket = socket;
    }

    @Override
    public void run(){
        System.out.println("Server accepted connection: " + socket);
        costumer = receiveCostumer();

        System.out.println(costumer.toString());

        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public CarService receiveCostumer(){

        CarService tmpCostumer = null;

        try {
            Scanner fromClient = new Scanner(socket.getInputStream());

            carID = fromClient.nextLine();
            carType = fromClient.nextLine();
            services = fromClient.nextLine();
            sum = fromClient.nextInt();

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            time = sdf.format(date);

            tmpCostumer = new CarService(carID, carType, services, sum);
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        return tmpCostumer;
    }
}

主窗口:

public class Window extends Application {

    private int fontSize = 25;
    public TableView tableView;
    public static Server server = null;

    public static void main(String[] args) {
        try {
            server = new Server();
        } catch (IOException e) {
            e.printStackTrace();
        }
        launch(args);
    }

    @Override
    public void start(Stage stageServer) {

        FileRegistration fr = new FileRegistration();

        tableView = new TableView();
        tableView.setPlaceholder(new Label("No entries to display here"));
        TableColumn<CarService, String> c1 = new TableColumn<>("Car ID");
        c1.setCellValueFactory(new PropertyValueFactory<>("carID"));
        c1.setEditable(false);
        c1.setPrefWidth(80.0);
        c1.setResizable(false);
        c1.setReorderable(false);
        TableColumn<CarService, String> c2 = new TableColumn<>("Car Type");
        c2.setCellValueFactory(new PropertyValueFactory<>("carType"));
        c2.setEditable(false);
        c2.setPrefWidth(80.0);
        c2.setResizable(false);
        c2.setReorderable(false);
        TableColumn<CarService, String> c3 = new TableColumn<>("Services");
        c3.setCellValueFactory(new PropertyValueFactory<>("servicesMessage"));
        c3.setEditable(false);
        c3.setPrefWidth(600.0);
        c3.setResizable(true);
        c3.setReorderable(false);
        TableColumn<CarService, String> c4 = new TableColumn<>("Summary");
        c4.setCellValueFactory(new PropertyValueFactory<>("sum"));
        c4.setEditable(false);
        c4.setPrefWidth(100.0);
        c4.setResizable(false);
        c4.setReorderable(false);

        tableView.getColumns().add(c1);
        tableView.getColumns().add(c2);
        tableView.getColumns().add(c3);
        tableView.getColumns().add(c4);

        // Insert will be done when a costumer arrives in the EchoServer class.
        //
        CarService cs1 = new CarService("TYA4567", "car", "1,7,8,9,", 187);
        CarService cs2 = new CarService("TRZ9876", "jeep", "3,6,7,10,", 114);
        CarService cs3 = new CarService("POD4567", "car", "1,7,8,9,10", 190);
        CarService cs4 = new CarService("YGD9876", "moto", "4,8,", 48);
        tableView.getItems().add(cs1);
        tableView.getItems().add(cs2);
        tableView.getItems().add(cs3);
        tableView.getItems().add(cs4);
        //

        TableViewSelectionModel<CarService> selectionModel = tableView.getSelectionModel();
        selectionModel.setSelectionMode(SelectionMode.SINGLE);

        // Setting up the layout of the buttons.
        Button remove = new Button("Remove");
        remove.setFont(new Font("arial", fontSize-5));
        remove.setTextAlignment(TextAlignment.CENTER);
        Button cash = new Button("Cash");
        cash.setFont(new Font("arial", fontSize-5));
        cash.setTextAlignment(TextAlignment.CENTER);

        HBox buttons = new HBox();
        buttons.setAlignment(Pos.CENTER);
        buttons.setPadding(new Insets(30.0));
        buttons.setSpacing(20.0);
        buttons.getChildren().addAll(remove, cash);

        // Setting up functions for the buttons.
        // Making remove button.
        remove.setOnAction(event -> {
            if (!selectionModel.isEmpty()){
                Alert alert = new Alert(AlertType.CONFIRMATION);
                alert.setTitle("Confirmation");
                alert.setHeaderText("Proceed with removal of the registry?\n");
                alert.setContentText(null);

                Optional<ButtonType> result = alert.showAndWait();
                if (result.isPresent()){
                    if (result.get() == ButtonType.OK){
                        tableView.getItems().remove(tableView.getSelectionModel().getSelectedIndex());
                        selectionModel.clearSelection();
                    } else{
                        selectionModel.clearSelection();
                        event.consume();
                    }
                }
            }
        });
        // Making cash button.
        cash.setOnAction(event -> {
            if (!selectionModel.isEmpty()){
                ObservableList<CarService> selectedCar = selectionModel.getSelectedItems();

                Alert alert = new Alert(AlertType.CONFIRMATION);
                alert.setTitle("Receipt");
                alert.setHeaderText("Proceed with transaction?\n");

                String receipt = "";
                for (int i = 0; i < selectedCar.get(0).getServices().size(); i++){
                    receipt = receipt + selectedCar.get(0).getServices().get(i) + " : " + selectedCar.get(0).getPrices().get(i) + "\n";
                }

                alert.setContentText("Car ID : " + selectedCar.get(0).getCarID() + "\n\n" + receipt + "\nSummary : " + selectedCar.get(0).getSum());

                Optional<ButtonType> result = alert.showAndWait();
                if (result.isPresent()){
                    if (result.get() == ButtonType.OK){

                        // Writing cashing to the registrations book.
                        fr.writeToFile(selectedCar.get(0));

                        tableView.getItems().remove(tableView.getSelectionModel().getSelectedIndex());
                        selectionModel.clearSelection();
                    } else{
                        selectionModel.clearSelection();
                        event.consume();
                    }
                }
            }
        });

        VBox mainServer = new VBox();
        mainServer.setAlignment(Pos.CENTER);
        mainServer.setPadding(new Insets(30.0));
        mainServer.setSpacing(20.0);
        mainServer.getChildren().addAll(tableView, buttons);

        // Setting up the close_window function.
        stageServer.addEventFilter(WindowEvent.WINDOW_CLOSE_REQUEST, event -> {
            ObservableList<CarService> items = tableView.getItems();
            if (items.size() > 0){
                Alert alert = new Alert(AlertType.ERROR);
                alert.setTitle("Warning");
                alert.setHeaderText("You can NOT exit when there are costumers waiting.");
                alert.setContentText(null);
                alert.showAndWait();
                event.consume();
            }
        });

        Scene stageScene = new Scene(mainServer, 1024, 768);
        stageServer.setTitle("Cash Desk");
        stageServer.setResizable(false);
        stageServer.setScene(stageScene);
        stageServer.show();
    }
}

我真的不是很好的线程处理,所以请,我需要解释性的答案,如果可能的话。
提前谢谢。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题