Excepción EOF en Java, mientras que el envío de múltiples archivos a través de conexión de socket único

somya Jain:

Estoy tratando de enviar varios archivos a través de sockets de Java. Después de recibir con éxito el primer archivo, se lanza EOFException. Soy incapaz de averiguar lo que va mal. (Todos los archivos se envían correctamente desde el lado del remitente)

Código del remitente:

    sendToServer = new Socket(receiver,port);
    DataOutputStream out = new DataOutputStream(sendToServer.getOutputStream());

    for(File f: file_to_send){

        sendMessage = f.getName() + "\n"+ f.length() + "\n";
        out.writeUTF(sendMessage);

        FileInputStream requestedfile = new FileInputStream(f.getPath());
        System.out.println("file path: "+f.getPath());

        int count;
        byte[] buffer = new byte[8192];
        while ((count = requestedfile.read(buffer)) > 0)
        {
            out.write(buffer, 0, count);
        }

        System.out.println("File transfer completed!! voila! :)");
        requestedfile.close();
    }

    out.close();
    sendToServer.close();

El código del receptor:

System.out.println("File Count : " + fileCount);
for (int count =0; count<fileCount; count++){
            String fileName = dis.readUTF();
            int length = Integer.parseInt(fileName.split("\n")[1]);
            fileName = fileName.split("\n")[0];
            System.out.println("File Name : " + fileName);
            System.out.println("Length : " + length);
            System.out.println("File Data : ");
            FileOutputStream fos = new FileOutputStream(new File(fileName));
            int c;
            byte[] buffer = new byte[8192];
            while ((c = dis.read(buffer)) > 0)
            {
                fos.write(buffer, 0, c);
                fos.flush();
            }
            fos.close();
            System.out.println("\nFile received successfully!!! voila !! :)");               
        }

Y la salida es la siguiente:

Files Count : 2
File Name : Belly Dance.3gp
Length : 15969978
File Data : 

File received successfully!!! voila !! :)
java.io.EOFException
at java.base/java.io.DataInputStream.readUnsignedShort(DataInputStream.java:345)
at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:594)
at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:569)
at App.java.DiscoveryClient.HandleInputMessage(DiscoveryClient.java:130)
at App.java.DiscoveryClient.run(DiscoveryClient.java:44)
at java.base/java.lang.Thread.run(Thread.java:834)
Joni:

El código que recibe el archivo no se detiene después de leer el primer archivo, pero mantiene la lectura hasta el final de la secuencia, escribir todo lo que se envía en el mismo archivo.

Es necesario hacer un seguimiento de la cantidad de bytes que ya ha leído y / o la cantidad de bytes que todavía tiene que leer:

        int remainingBytes = length;
        while (remainingBytes > 0 && (c = dis.read(buffer, 0, Math.min(buffer.length, remainingBytes))) > 0)
        {
            remainingBytes -= c;
            fos.write(buffer, 0, c);
            // fos.flush(); this is not really necessary
        }

Por cierto, el uso intde la longitud del archivo se limita a los archivos de 2 GB como máximo. Si esto es un problema, utilice longen lugar de int.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=217606&siteId=1
Recomendado
Clasificación