отправлять изображения через сокеты, не повреждая их - PullRequest
0 голосов
/ 18 января 2020

Здравствуйте, ребята, я пытаюсь написать приложение android для отправки изображения через p c через сокет. У меня есть клиент android и сервер Java SE. Иногда изображения приходят поврежденными, и я не знаю почему. Я попытался отправить 175 фотографий, и 9 из них повреждены. это код для android клиента: PS: я использую ObjectInputStream и ObjectInputstream.

            try {

                //Get image
                //the variable "uri" is the uri of image
                InputStream is =  contentResolver.openInputStream(uri);
                final Bitmap bitmap = BitmapFactory.decodeStream(is);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte array[] = baos.toByteArray();
                int length = array.length;
                Log.d("MY-DEBUG", "length: " + length);

                //Send lenght of image
                out.writeInt(length);
                out.flush();

                int remainent = length;
                int send = 0;
                int size = SIZE;

                while (remainent > 0) {
                    if (remainent < size)
                        size = remainent;

                    //System.out.println("ATTUALE: " + send + ", GRANDEZZA ARRAY: " + size);
                    out.write(array, send, size);
                    int percentage = (100 * send) / length;
                    publishProgress(percentage);
                    System.out.println("\n === FINE === \n");

                    send += size;
                    remainent -= size;
                    Log.d("MY-DEBUG", "Send " + send + "/" + length + " - remainent: " + remainent);
                }

                out.flush();

                Log.d("MY-DEBUG", "Immagine inviata");
                publishProgress(0);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

, и это код для сервера в Java SE

try {           
        //Read length
        int length = (int) in.readInt();

        File target = new File(percorso + "\\img-" + sequenza + ".jpg");
        outs = new FileOutputStream(target, true);
        System.out.println("Grandezza: " + length);
        int remainent = length;
        int read = 0;
        int total = 0;
        int size = SIZE;

        byte buffer[] = new byte[size];

        while ((read = in.read(buffer, 0, size)) != -1) {                           
            total += read;
            remainent = length - total;
            System.out.println("read: " + read + " - Received: " + total + "/" + length + " - remainent: " + remainent);
            int percentuale = (100 * total) / length;
            progressBar.setValue(percentuale);
            outs.write(buffer);
            outs.flush();

            Thread.sleep(1);
            if (remainent == 0) break;
        }

        progressBar.setValue(0);

        //Thread.sleep(100);

        //in.read();

        System.out.println("END");
    } catch (IOException e1) {
        System.err.println(e1.getMessage());
        e1.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (outs != null) {
            try {
                outs.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    outs.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
        Thread.currentThread().interrupt();
    }

SIZE. объявляется так:

private static final int SIZE = 1024;

Если я установлю значение> 1024, ВСЕ фотографии будут повреждены. Если я использую 1024, некоторые фотографии приходят поврежденными. Большое спасибо

1 Ответ

0 голосов
/ 18 января 2020

Проблема заключается в следующей строке:

outs.write(buffer);

Вы безоговорочно записываете весь буфер, который всегда имеет длину SIZE байт. Но что, если у вас было "короткое" чтение ? Попробуйте вместо этого:

outs.write(buffer,0,read);
...