Chikage
Chikage

Reputation: 329

Java Socket Corrupting PNG-image

I am currently trying to use a Socket to send a PNG or JPEG image from one Client to another (in Java) but the images always becomes corrupted (when I try to open it it just says that it can't be opened because it's damaged, faulty or too big). I have tried the methods that load the images into byte[] and if I just load an image into a byte[] and then save it back down it works perfectly so the problem must be in the sending of the byte[]. Here are the functions I use for the sending:

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

The images that arrive seems to be the correct size and all so the data is at least arriving, just corrupted.

Upvotes: 0

Views: 483

Answers (1)

user207421
user207421

Reputation: 310850

Throw your receiveData() method away and use DataInputStream.readFully().

Upvotes: 3

Related Questions