You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Socket编程:字符串数组收发失败问题排查及解决

Fixing Your Java Socket Data Transfer Issue

Let's walk through exactly why your server isn't receiving data, and fix both the client and server code to get your longest consecutive sequence logic working properly.

Core Problems in Your Current Code

1. Server Isn't Actually Reading Input Data

The biggest issue is this line in your server code:

String[] numbers = is.toString().split(" ");

Calling toString() on a DataInputStream doesn't read the data sent from the client—it just returns a generic object string (like java.io.DataInputStream@abc123). You're not pulling any actual bytes from the socket input stream here, so your numbers array is always going to be broken.

2. Client Sends Data Without Clear Boundaries

Your client loops through each number string and sends its bytes directly:

for (int i = 0; i < size; ++i) {
    os.write(numbers[i].getBytes());
    os.flush();
}

This sends bytes like '5', '2', '1' '2' (for "12") with no separators. Even if the server was reading correctly, it couldn't tell where one number ends and the next begins. Plus, the server has no way of knowing when all data has been sent.

Solutions to Fix the Data Transfer

We have two straightforward approaches to fix this—pick whichever fits your needs better.

Approach 1: Send the Entire Input String (Simplest)

Since your client already reads the user's input as a single string, just send that whole string to the server. Java's DataOutputStream.writeUTF() and DataInputStream.readUTF() handle sending the string length automatically, so the server knows exactly how much data to read.

Modified Client Code (Relevant Parts)

// After getting sarray from user input
os.writeUTF(sarray); // Send the entire input string
os.flush();

// Read the server's responses (note: server will send two lines now)
System.out.println(is.readLine());
System.out.println(is.readLine());

Modified Server Code (Relevant Parts)

// Read the entire string from client
String input = is.readUTF();
String[] numbers = input.split(" ");

// Convert to int array (same as before)
int size = numbers.length;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
    arr[i] = Integer.parseInt(numbers[i]);
}

// Your longest consecutive sequence logic (updated to capture the actual sequence)
HashSet<Integer> numSet = new HashSet<>();
for (int num : arr) {
    numSet.add(num);
}

int maxLength = 0;
List<Integer> longestSequence = new ArrayList<>();

for (int num : arr) {
    // Check if this is the start of a sequence
    if (!numSet.contains(num - 1)) {
        int currentNum = num;
        List<Integer> currentSequence = new ArrayList<>();
        
        while (numSet.contains(currentNum)) {
            currentSequence.add(currentNum);
            currentNum++;
        }
        
        // Update max sequence if current is longer
        if (currentSequence.size() > maxLength) {
            maxLength = currentSequence.size();
            longestSequence = currentSequence;
        }
    }
}

// Send both length and sequence back to client
os.println("Length of longest Consecutive Sequence = " + maxLength);
os.println("Longest Consecutive Sequence values are: " + longestSequence);
os.flush();

Approach 2: Send Integer Data Directly (More Efficient)

If you want to avoid string parsing overhead, send the array length first, then send each integer as raw binary data.

Modified Client Code (Relevant Parts)

// After converting to int array arr
os.writeInt(size); // Send the size of the array first
for (int num : arr) {
    os.writeInt(num); // Send each integer
}
os.flush();

// Read server responses
System.out.println(is.readLine());
System.out.println(is.readLine());

Modified Server Code (Relevant Parts)

// Read array size first
int size = is.readInt();
int[] arr = new int[size];

// Read each integer
for (int i = 0; i < size; i++) {
    arr[i] = is.readInt();
}

// Same longest sequence logic as Approach 1 here...

// Send results back to client
os.println("Length of longest Consecutive Sequence = " + maxLength);
os.println("Longest Consecutive Sequence values are: " + longestSequence);
os.flush();

Why This Works

  • Clear Data Boundaries: Both methods tell the server exactly how much data to read (either via the string length in writeUTF, or the explicit array size in writeInt).
  • Proper Input Reading: The server now actually reads bytes from the socket stream instead of using toString().
  • Complete Results: We updated the server to return both the length and the actual sequence, matching your business requirements.

Testing with your example input 5 2 12 4 3 9, the client will now correctly receive:

Length of longest Consecutive Sequence = 4
Longest Consecutive Sequence values are: [2, 3, 4, 5]

内容的提问来源于stack exchange,提问作者Michael Maguire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:18:09