Клиентский класс не может открыться, пока я открываю серверный класс! - PullRequest
0 голосов
/ 05 марта 2019

В настоящее время я пытаюсь создать простую программу, которая отправляет целочисленный массив с клиента на сервер.затем SERVER сортирует массив обратно в CLIENT, каждый класс использует JavaFX для создания этапа отображения сообщения.НО я не знаю, почему, когда я открываю сервер, а затем открываю клиент, клиент не отвечает.

 public class Client extends Application {

//IO Streams of data
ObjectOutputStream toServer = null;
ObjectInputStream fromServer = null;
final int size = 1000; //list size
int[] list = new int[size];
int[] list2 = new int[size];
Random randomNum = new Random();

@Override
public void start(Stage primaryStage) {

    //propeties of the layouts
    TextArea textConsole = new TextArea();
    Button random = new Button("random");
    Button send = new Button("send");

    HBox buttons = new HBox();
    buttons.getChildren().addAll(random, send);
    VBox vbox = new VBox();
    vbox.getChildren().addAll(textConsole, buttons);

    //create a scene to place it in the stage
    Scene scene = new Scene(vbox, 450, 300);
    primaryStage.setTitle("Cilent");
    primaryStage.setScene(scene);
    primaryStage.show();

    //random the number from -2000 to 2000
    for (int i = 0; i < list.length; i++) {
        list[i] = ((int) randomNum.nextInt(2000 - (-2000) + 1) - 2000);
        // System.out.println("number is "+list[i]);
    }

    //set action on random button.
    random.setOnAction(e -> {

        try {
            //send array to server
            toServer.writeObject(list);
            toServer.flush();

            //get sorted list from the server
            list2 = (int[]) fromServer.readObject();

            //display the text into console
            for (int i = 0; i < list2.length; i++) {
                textConsole.appendText("Number is " + list2[0] + "\n");
            }

        } catch (Exception ex) {

            textConsole.appendText(ex.toString() + "\n");
        }

    });
    //set connection
    try {
        //create a socket to connect to the server;
        Socket socket = new Socket("localhost", 8000);

        //create an input stream to receve data from the server
        fromServer = new ObjectInputStream(socket.getInputStream());

        //create an ouput stream to send data to server
        toServer = new ObjectOutputStream(socket.getOutputStream());
    } catch (IOException ex) {
        textConsole.appendText(ex.toString() + "\n");
    }

}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

} открытый класс Сервер расширяет приложение {

//array list to hold the data 
int[] list = new int[1000];

@Override
public void start(Stage primaryStage) {

    //text area for displaying the contents 
    TextArea textConsole = new TextArea();

    Scene scene = new Scene(new ScrollPane(textConsole), 300, 250);
    primaryStage.setTitle("Server");
    primaryStage.setScene(scene);
    primaryStage.show();

    new Thread(() -> {

        try {   //create a server socket
            ServerSocket serverSocket = new ServerSocket(8000);

            Platform.runLater(()
                    -> textConsole.appendText("Server started at" + new Date() + "\n"));

            //listen for a conncetion request
            Socket socket = serverSocket.accept();

            //create data input and output 
            ObjectInputStream fromCilent = new ObjectInputStream(socket.getInputStream());

            ObjectOutputStream toCilent = new ObjectOutputStream(socket.getOutputStream());

            while (true) {

                try {
                    //received the array list from cilent                   
                    list = (int[]) fromCilent.readObject();

                    //once recevied the data, make a merge sort 
                    ParallelMergeSort.parallelMergeSort(list);
                    //send back to cilent
                    toCilent.writeObject(list);

                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                //updated the UI
                Platform.runLater(() -> {

                    for (int i = 0; i < list.length; i++) {
                        textConsole.appendText("data received from Cilent:" + list[i] + '\n');
                    }

                });

            }

        } catch (IOException ex) {
            textConsole.appendText(ex.toString() + "\n");

        }

    }).start();//start the thread
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...