Как отправить и получить массив строк от клиента к серверу при программировании сокетов Java - PullRequest
0 голосов
/ 09 апреля 2020

// Здесь находится клиентская часть на стороне клиента. Я не знаю, почему мой сервер не получает данные, передает через массив неправильный способ сделать это, и если да, то есть ли другие решения, на которые я мог бы обратить внимание?

System.out.println("Trying to Connect to Server");
            // connect to server and extract input and output streams
            try (Socket serverSocket = new Socket(hostName, hostPort);
                    DataOutputStream os = new DataOutputStream(new BufferedOutputStream(serverSocket.getOutputStream()));
                    BufferedReader is = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()))) {

            // create client input stream for user input
            Scanner scanners = new Scanner(System.in); //create scanner object
            System.out.println("Enter the number sequence you wish to be checked");
            String sarray = scanners.nextLine();
            numbers = sarray.split(" ");
            //System.out.println(Arrays.toString(numbers));
            int size = numbers.length;
            int[] arr = new int[size];
            for (int i = 0; i < size; i++) {
                arr[i] = Integer.parseInt(numbers[i]);
            }

            // send the values to the server
            for (int i = 0; i < size; ++i) {
                os.write(numbers[i].getBytes());
                os.flush();
            }


            // read message back from server
            System.out.println(is.readLine());

        } catch (Exception e) {
            System.err.println("Exception:  " + e.getMessage());
        }
    }

// Вот часть серверной части. Клиент принимает последовательность целочисленных значений переменной длины от пользователя и передает их на сервер для обработки. Сервер находит наибольшую последовательную подпоследовательность и возвращает клиенту длину этой подпоследовательности, за которой следует подпоследовательность. Затем клиент отображает пользователю длину подпоследовательности, за которой следует подпоследовательность.

//accept client connection
                Socket clientSocket = serverSocket.accept();
                try (DataInputStream is = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                        PrintWriter os = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())))) {
                    System.out.println("Client Accepted");
                    //read array numbers from client
                    String[] numbers = is.toString().split(" ");
                    // decide the response
                    int size = numbers.length;
                    int[] arr = new int[size];
                    for (int i = 0; i < size; i++) {
                        arr[i] = Integer.parseInt(numbers[i]);
                    }
                    int n = arr.length;
                    HashSet<Integer> a = new HashSet<>();
                    int ans = 0;
                    // Hash all the array elements
                    for (int i = 0; i < n; ++i) {
                        a.add(arr[i]);
                    }
                    // check each possible sequence from the start
                    // then update optimal length
                    for (int i = 0; i < n; ++i) {
                        // if current element is the starting
                        // element of a sequence
                        if (!a.contains(arr[i] - 1)) {
                            // Then check for next elements in the
                            // sequence
                            int j = arr[i];
                            while (a.contains(j)) {
                                j++;
                            }
                            // update optimal length if this length
                            // is more
                            if (ans < j - arr[i]) {
                                ans = j - arr[i];
                            }
                        }
                    }
                    System.out.println(a.toString());
                    System.out.println("Length of longest Consecutive Sequence = " + ans);
                    os.println(ans);
                    os.flush();
                    System.out.println("Session Over");
                } catch (IOException e) {
                    System.out.println("IOException:" + e.getMessage());
                }
            }//end while
        } catch (IOException e) {
            System.out.println("IOException:" + e.getMessage());
        }
    }//end main
}

// Ожидаемый результат будет: Если вы введете, например, следующие шесть чисел: 5 2 12 4 3 9 Вы вернется: Длина самой длинной последовательной последовательности = 4. Самые длинные значения последовательной последовательности: [2, 3, 4, 5]

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