0

我正在开发一个cient/server java 应用程序。我写了两个类,一个用于发送文件,一个用于接收文件。唯一的问题是有时只发送了一半字节(不知道为什么)并且客户端被阻塞等待另一半到达。我在我的机器上同时运行客户端和服务器进行测试。如何确保所有字节都无损发送?

文件发件人:

        OutputStream out = mSocket.getOutputStream();
        FileInputStream fileIn = new FileInputStream(mFile);

        long startTime = System.currentTimeMillis();

        /* Send bytes. */
        byte[] buffer = new byte[BUFFER_SIZE];
        int read;
        int readTotal = 0;

        while ((read = fileIn.read(buffer)) != -1) {
                out.write(buffer, 0, read);
                readTotal += read;
        }
        out.flush();

        long endTime = System.currentTimeMillis();
        System.out.println("\t" + readTotal + " bytes written in " + (endTime - startTime) + " ms.");

文件接收器:

        InputStream in = mSocket.getInputStream();

        long startTime = System.currentTimeMillis();

        /* Read bytes. */
        byte[] buffer = new byte[BUFFER_SIZE];
        int read;
        int totalRead = 0;

        FileOutputStream fileOut = new FileOutputStream(mLocalFolder + "/" + mFileName);

        while (totalRead < mSize) {

            read = in.read(buffer);
            fileOut.write(buffer);
            totalRead += read;
            System.out.println("SO FAR " + totalRead + " OUT OF " + mSize);
        }
        fileOut.close();

        long endTime = System.currentTimeMillis();
        System.out.println("\tComplete. " + totalRead + " bytes read in " + (endTime - startTime) + "ms.");
4

0 回答 0