Java Socket破坏了PNG图像

时间:2015-02-11 16:11:58

标签: java image sockets transfer corruption

我目前正在尝试使用Socket将PNG或JPEG图像从一个客户端发送到另一个客户端(使用Java),但图像总是被破坏(当我尝试打开它时它只是说它无法打开因为它已经损坏,有缺陷或太大了。 我已经尝试了将图像加载到byte []中的方法,如果我只是将图像加载到byte []中然后将其保存回来,则它可以完美地工作,所以问题必须在于发送byte []。 以下是我用于发送的功能:

/**
 * 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;
    }
}

到达的图像似乎是正确的大小,所有这些数据至少到达,只是已损坏。

1 个答案:

答案 0 :(得分:2)

抛弃receiveData()方法并使用DataInputStream.readFully()