【问题标题】:Java Socket Corrupting PNG-imageJava Socket 损坏 PNG-图像
【发布时间】:2015-02-11 16:11:57
【问题描述】:

我目前正在尝试使用套接字将 PNG 或 JPEG 图像从一个客户端发送到另一个客户端(在 Java 中),但图像总是损坏(当我尝试打开它时,它只是说它无法打开因为它已损坏、有故障或太大)。 我已经尝试了将图像加载到字节 [] 中的方法,如果我只是将图像加载到字节 [] 中,然后将其保存下来,它可以完美地工作,所以问题一定出在字节 [] 的发送中。 以下是我用于发送的函数:

/**
 * Attempts to send data through the socket with the BufferedOutputStream. <p>
 * Any safety checks should be done beforehand
 * @param data - the byte[] containing the data that shall be sent
 * @return - returns 'true' if the sending succeeded and 'false' in case of IOException
 */
public boolean sendData(byte[] data){
    try {
        //We simply try to send the data
        outS.write(data, 0, data.length);
        outS.flush();
        return true;    //Success
    } catch (IOException e) {
        e.printStackTrace();
        return false;   //Failed
    }
}

/**
 * Attempts to receive data sent to the socket. It uses a BufferedInputStream
 * @param size - the number of bytes that should be read
 * @return - byte[] with the received bytes or 'null' in case of an IOException
 */
public byte[] receiveData(int size){
    try {
        int read = 0, r;
        byte[] data = new byte[size];
        do{
            //We keep reading until we have gotten all data
            r = inS.read(data, read, size-read);
            if(r > 0)read += r;
        }while(r>-1 && read<size);  //We stop only if we either hit the end of the 
                            //data or if we have received the amount of data we expected
        return data;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

到达的图像似乎大小正确,因此数据至少到达了,只是损坏了。

【问题讨论】:

  • 请说明outSinS 的定义以及它们的定义和设置方式。创建时的源代码是什么?
  • 您是否尝试过使用 Apache Commons-IO 的 IOUtils.toByteArray(inputStream) 方法读取字节数组?
  • 我刚刚做了一个程序来比较发送图像中的每个字节,我发现发送图像中的所有字节都变成了零!我还想补充一点,如果我要发送 PDF,这些方法可以完美运行,到达后可以正常阅读
  • inS = BufferedInputStream, outS = BufferedOutputStream
  • 如果你到达流的末尾,你会返回一个全零的字节数组。

标签: java image sockets transfer corruption


【解决方案1】:

扔掉你的receiveData()方法并使用DataInputStream.readFully()

【讨论】:

  • 我试过用那个。同样的结果,图像失败(虽然它说它现在只有 1 kB 大,而不是应该的 9 MB)并且 PDF 确实通过了,但它小了几 kB(仍然可以打开,可能是一些文本得到了丢失)
  • 那你没做对。贴出代码。它适用于其他所有人。它通过了 JDK QA,并且已经做了将近 20 年。
猜你喜欢
  • 1970-01-01
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-22
  • 2012-10-20
  • 2019-05-11
相关资源
最近更新 更多