Отправляйте файл (изображение, текст или почтовый индекс), не закрывая сокет TCP Java [duplicate]

Я нашел математический способ выполнить эту работу

Github repo - https://github.com/gayanSandamal/easy-php-image-resizer

]

Пример в реальном времени - https://plugins.nayague.com/easy-php-image-resizer/

 $after_width) {

    //get the reduced width
    $reduced_width = ($width - $after_width);
    //now convert the reduced width to a percentage and round it to 2 decimal places
    $reduced_radio = round(($reduced_width / $width) * 100, 2);

    //ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
    $reduced_height = round(($height / 100) * $reduced_radio, 2);
    //reduce the calculated height from the original height
    $after_height = $height - $reduced_height;

    //Now detect the file extension
    //if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
    if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
        //then return the image as a jpeg image for the next step
        $img = imagecreatefromjpeg($source_url);
    } elseif ($extension == 'png' || $extension == 'PNG') {
        //then return the image as a png image for the next step
        $img = imagecreatefrompng($source_url);
    } else {
        //show an error message if the file extension is not available
        echo 'image extension is not supporting';
    }

    //HERE YOU GO :)
    //Let's do the resize thing
    //imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
    $imgResized = imagescale($img, $after_width, $after_height, $quality);

    //now save the resized image with a suffix called "-resized" and with its extension. 
    imagejpeg($imgResized, $filename . '-resized.'.$extension);

    //Finally frees any memory associated with image
    //**NOTE THAT THIS WONT DELETE THE IMAGE
    imagedestroy($img);
    imagedestroy($imgResized);
}
?>

20
задан Tom 5 28 April 2012 в 22:35
поделиться

2 ответа

Вы читаете сокет до тех пор, пока read() не вернет -1. Это условие конца потока (EOS). EOS происходит, когда партнер завершает соединение. Не когда он заканчивает запись одного файла.

Вам нужно отправить размер файла перед каждым файлом. Вы уже делаете подобное с количеством файлов. Затем убедитесь, что вы прочитали точно столько байтов для этого файла:

String filename = dis.readUTF();
long fileSize = dis.readLong();
FileOutputStream fos = new FileOutputStream(filename);
while (fileSize > 0 && (n = dis.read(buf, 0, (int)Math.min(buf.length, fileSize))) != -1)
{
  fos.write(buf,0,n);
  fileSize -= n;
}
fos.close();

Вы можете заключить все это в цикл, который завершается, когда readUTF() выбрасывает EOFException. Наоборот, вы должны вызывать writeUTF(filename) и writeLong(filesize) у отправителя перед отправкой данных.

23
ответ дан user207421 25 August 2018 в 06:17
поделиться

Я сделал это так, он работает отлично, вы можете взглянуть:

send

byte[] done = new byte[3];
String str = "done";  //randomly anything
done = str.getBytes();
for(int i =0; i < files.size(); i++){
    System.out.println(files.get(i).getName());
    FileInputStream fis = new FileInputStream(files.get(i));
    while((n =fis.read(buf)) != -1){
        dos.write(buf,0,n);
        System.out.println(n);
        dos.flush();
    }
 //should i close the dataoutputstream here and make a new one each time?                 
    dos.write(done,0,3);
    dos.flush();
}
        //or is this good?
        dos.close();

recieve

for(int i = 0; i < files.size();i++){
    System.out.println("Receiving file: " + files.get(i).getName());
 //create a new fileoutputstream for each new file
fos = new FileOutputStream("C:\\users\\tom5\\desktop\\salestools\\" +files.get(i).getName());
//read file
while((n = dis.read(buf)) != -1 && n!=3 ){
        fos.write(buf,0,n);
        fos.flush();
        }
            fos.close();
        }
1
ответ дан Nikhar 25 August 2018 в 06:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: