简体   繁体   English

Android / Java-如何检查OutputStream完成写入字节的时间

[英]Android/Java - How check when the OutputStream has finished to write the bytes

I have created a server socket that accept a connection from a client, and when the connection is established an image is transferred to it using the OutputStream that write the bytes. 我创建了一个服务器套接字,该套接字接受来自客户端的连接,建立连接后,将使用写入字节的OutputStream将图像传输到该套接字。 My question is how can i check if the OutputStream has finished to write the bytes before close the socket connection, because sometimes not all the image is correctly transferred. 我的问题是我如何在关闭套接字连接之前检查OutputStream是否已完成写入字节,因为有时并非所有图像都已正确传输。 This is the code that i'm using: 这是我正在使用的代码:

File photoFile = new File(getHeader); //getHeader is the file that i have to transfer
int size2 = (int) photoFile.length();
byte[] bytes2 = new byte[size2];
try {
    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(photoFile)); 
    buf.read(bytes2, 0, bytes2.length);
    buf.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }
    client.getOutputStream().write(bytes2, 0, size2); //client is the server socket

Thanks 谢谢

My question is how can i check if the OutputStream has finished to write the bytes before close the socket connection, because sometimes not all the image is correctly transferred 我的问题是我如何在关闭套接字连接之前检查OutputStream是否已完成写入字节,因为有时并非所有图像都已正确传输

No, your problem is that you are assuming that read() fills the buffer. 不,您的问题是您假设read()填充了缓冲区。 The OutputStream has finished writing when the write returns. 写入返回时, OutputStream已完成写入。 Memorize this: 记住这一点:

while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

This is the correct way to copy streams in Java. 这是在Java中复制流的正确方法。 Yours isn't. 你不是。

You are also assuming that the file size fits into an int, and that the entire file fits into memory, and you are wasting both time and space reading the entire file (maybe) into memory before writing anything. 您还假设文件大小适合一个int,并且整个文件适合内存,并且浪费时间和空间将整个文件(也许)读入内存,然后再进行任何写操作。 The code above works for any size buffer from 1 byte upwards. 上面的代码适用于1字节以上的任何大小的缓冲区。 I usually use 8192 bytes. 我通常使用8192字节。

A common solution is to prefix the data with a number of bytes (say four) that describe the length of the data being sent. 常见的解决方案是为数据添加描述所发送数据长度的多个字节(例如四个字节)作为前缀。

The receiving server reads the first four bytes, calculates the length and knows when it has finished reading the file. 接收服务器读取前四个字节,计算长度,并知道何时完成读取文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM