如何在Java套接字编程中从客户端发送和接收字符串数组到服务器。

huangapple 未分类评论47阅读模式
英文:

How do I send and receive an string array from client to server in Java socket programming

问题

// 下面是客户端的部分。我不知道为什么服务器没有接收到数据,通过数组传递是否是错误的方式,如果是的话,是否有其他解决方案可以查看?

System.out.println("尝试连接服务器");
// 连接服务器并提取输入输出流
try (Socket serverSocket = new Socket(hostName, hostPort);
        DataOutputStream os = new DataOutputStream(new BufferedOutputStream(serverSocket.getOutputStream()));
        BufferedReader is = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()))) {

    // 为用户输入创建客户端输入流
    Scanner scanners = new Scanner(System.in); // 创建扫描器对象
    System.out.println("输入要检查的数字序列");
    String sarray = scanners.nextLine();
    numbers = sarray.split(" ");
    int size = numbers.length;
    int[] arr = new int[size];
    for (int i = 0; i < size; i++) {
        arr[i] = Integer.parseInt(numbers[i]);
    }

    // 将值发送到服务器
    for (int i = 0; i < size; ++i) {
        os.write(numbers[i].getBytes());
        os.flush();
    }

    // 从服务器读取消息
    System.out.println(is.readLine());

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

// 下面是服务器端的部分。客户端接受用户的变长整数序列,并将其提交给服务器进行处理。服务器找到最大的连续子序列,然后返回给客户端这个子序列的长度,接着是子序列本身。客户端然后向用户显示子序列的长度,然后是子序列本身。

// 接受客户端连接
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("客户端已连接");
    // 从客户端读取数组数字
    String[] numbers = is.toString().split(" ");
    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;
    // 对所有数组元素进行哈希处理
    for (int i = 0; i < n; ++i) {
        a.add(arr[i]);
    }
    // 检查从开始位置的每个可能的序列
    // 然后更新最优长度
    for (int i = 0; i < n; ++i) {
        // 如果当前元素是序列的起始元素
        if (!a.contains(arr[i] - 1)) {
            // 然后检查序列中的下一个元素
            int j = arr[i];
            while (a.contains(j)) {
                j++;
            }
            // 如果这个长度更长,则更新最优长度
            if (ans < j - arr[i]) {
                ans = j - arr[i];
            }
        }
    }
    System.out.println(a.toString());
    System.out.println("最长连续序列的长度 = " + ans);
    os.println(ans);
    os.flush();
    System.out.println("会话结束");
} catch (IOException e) {
    System.out.println("I/O 异常: " + e.getMessage());
}
// 预期输出将是:
如果你例如输入以下六个数字:
5  2  12  4 3  9 
你将会得到:
最长连续序列的长度 = 4
最长连续序列的值为: [2, 3, 4, 5]
英文:

// Heres the client part of the client-side. I Don't know why my server isn't receiving the data, is feeding through an array the wrong way to do it and if so is there any other solutions I could look at?

System.out.println(&quot;Trying to Connect to Server&quot;);
            // 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(&quot;Enter the number sequence you wish to be checked&quot;);
            String sarray = scanners.nextLine();
            numbers = sarray.split(&quot; &quot;);
            //System.out.println(Arrays.toString(numbers));
            int size = numbers.length;
            int[] arr = new int[size];
            for (int i = 0; i &lt; size; i++) {
                arr[i] = Integer.parseInt(numbers[i]);
            }

            // send the values to the server
            for (int i = 0; i &lt; 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(&quot;Exception:  &quot; + e.getMessage());
        }
    }

// Heres part of the server-side. The client accepts a variable-length sequence of integer values from the user and submits them to the server for processing. The server finds the largest consecutive subsequence and returns to the client the length of this subsequence followed by the subsequence. The client then displays to the user the length of the subsequence followed by the subsequence.

//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(&quot;Client Accepted&quot;);
                    //read array numbers from client
                    String[] numbers = is.toString().split(&quot; &quot;);
                    // decide the response
                    int size = numbers.length;
                    int[] arr = new int[size];
                    for (int i = 0; i &lt; size; i++) {
                        arr[i] = Integer.parseInt(numbers[i]);
                    }
                    int n = arr.length;
                    HashSet&lt;Integer&gt; a = new HashSet&lt;&gt;();
                    int ans = 0;
                    // Hash all the array elements
                    for (int i = 0; i &lt; n; ++i) {
                        a.add(arr[i]);
                    }
                    // check each possible sequence from the start
                    // then update optimal length
                    for (int i = 0; i &lt; 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 &lt; j - arr[i]) {
                                ans = j - arr[i];
                            }
                        }
                    }
                    System.out.println(a.toString());
                    System.out.println(&quot;Length of longest Consecutive Sequence = &quot; + ans);
                    os.println(ans);
                    os.flush();
                    System.out.println(&quot;Session Over&quot;);
                } catch (IOException e) {
                    System.out.println(&quot;IOException:&quot; + e.getMessage());
                }
            }//end while
        } catch (IOException e) {
            System.out.println(&quot;IOException:&quot; + e.getMessage());
        }
    }//end main
}

// Expected output would be:
If you input for example the following six numbers:
5 2 12 4 3 9
You will get back:
Length of longest Consecutive Sequence = 4
Longest Consecutive Sequence values are: [2, 3, 4, 5]

huangapple
  • 本文由 发表于 2020年4月9日 21:01:21
  • 转载请务必保留本文链接:https://java.coder-hub.com/61121789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定