从输入流读取的第二个数据包的数据不完整



i使用TCP接收字节,然后将其保存到文件流中。通过许多测试,我已经看到收到的第一个数据包始终只是没有其他数据的文件名。第二个数据包仅具有一个字节,它是输入文本文件的第一个字母。在此之后,所有数据包都正确发送,但是我似乎无法弄清楚是什么弄乱了第二个数据包。似乎最后一个数据包写了两次。谁能看到我做错了什么?这是一个示例输入/输出:https://www.diffchecker.com/srclclrx

    InputStream in = clntSock.getInputStream(); //server's input stream - gets data from the client
        OutputStream out = clntSock.getOutputStream(); //server's output stream - server sends data to the client
        byte[] byteBuffer = new byte[BUFSIZE];
        int count = in.read(byteBuffer, 0, BUFSIZE);
        String firstRead = new String(byteBuffer, 0, count);
        int fileNameEnd = firstRead.indexOf("rn");
        String fileName = firstRead.substring(0, fileNameEnd);
        FileOutputStream fout = new FileOutputStream(fileName); //unzipped file output stream
        int contentBegin = fileNameEnd+2;
        byte[] oldBuffer = Arrays.copyOfRange(byteBuffer, contentBegin, count);
        int oldCount = count-contentBegin;
        String oldString = new String(byteBuffer, contentBegin, count-contentBegin, "US-ASCII");
        while((count = in.read(byteBuffer, 0, BUFSIZE)) != -1) { // read from origin's buffer into byteBuffer until origin is out of data
            String newString = new String(byteBuffer, 0, count, "US-ASCII");
            String combinedString = oldString + newString;
            int index = combinedString.indexOf("--------MagicStringCSE283Miami");
            if(index != -1){
                System.out.println("Final Print");
                byte[] combinedBuffer = concat(oldBuffer, byteBuffer);
                for(int i=0; i<index; i++){
                    System.out.print((char)combinedBuffer[i]);
                }
                System.out.println("");
                fout.write(combinedBuffer, 0, index);
                fout.flush();
                fout.close();
                break;
            }
            System.out.println(+ oldCount);
            fout.write(oldBuffer, 0, oldCount); //write the byteBuffer's data to the client via the zip output stream
            fout.flush(); //push all data out of the zipOutputStream before continuing
            if(count == 1){
                for(int i=0; i<count; i++){
                    System.out.println((char)byteBuffer[i]);
                }
            }
            oldBuffer = byteBuffer;
            oldCount = count;
            oldString = newString;
        }

编辑:对我的另一个特点是,第二个数据包始终只是" - ",然后最后一个数据包具有终止文件输出流的魔术字符串的其余部分。

您是否真的确定您正在获取收到的数据的全部内容?

while((count = in.read(byteBuffer, 0, BUFSIZE)) != -1) { // read from origin's buffer into byteBuffer until origin is out of data
     add logic here to print count
     add logic here to print the content of the byteBuffer 
}

在您的逻辑上,您很可能会虐待收到的内容,并以某种方式放松数据的部分。例如,您声称仅收到' - '的第二个数据包,而计数是等于1吗?TCP确实可能是这种情况,但是您确实必须验证您确实正在处理收到的所有内容。根据您的解释,我认为您正在删除数据,但实际上不是正确处理。

TCP中没有消息,并且不能保证每个read()将返回多少数据。除非发生错误,否则仅指定至少在阻塞模式下传输一个字节。

这样做的结果之一是,不可能在变量中存储read()的结果,对其进行测试,然后使用它来界定处理的数据量。

您的期望有错。

相关内容

最新更新