Transfert d'un fichier d'une machine a une autre par socket

-
Bonjour,
je veux transférer des fichiers d'une machine a une autre en utilisant les sockets donc j'ai pensé a utiliser cela comme debut. j'ai donc fait 3 classes comme suit :
pour le client :

import java.io.*;
 
import java.net.Socket;
 
 
 
public class Client {
 
    private Socket socket = null;
 
    private boolean isConnected = false;
 
    private ObjectOutputStream outputStream = null;
 
    private String sourceDirectory = "C:/Users/administrateur/workspace/PFFF/poli 1.txt";
 
    private String destinationDirectory = "C:/Users/administrateur/workspace";
 
    private int fileCount = 0;
 
    private FileEvent fileEvent = null;
 
 
 
    public Client() {
 
 
 
    }
 
 
 
    public void connect() {
 
        while (!isConnected) {
 
            try {
 
                socket = new Socket("localHost", 4445);
 
                outputStream = new ObjectOutputStream(socket.getOutputStream());
 
                isConnected = true;
 
            } catch (IOException e) {
 
                e.printStackTrace();
 
            }
 
        }
 
    }
 
 
 
    public void locateFiles() {
 
        File srcDir = new File(sourceDirectory);

        if (!srcDir.isDirectory()) { 
            System.out.println("Source directory is not valid ..Exiting the client");
 
            System.exit(0);
 
        }
 
        File[] files = srcDir.listFiles();
 
        fileCount = files.length;
 
        if (fileCount == 0) {
 
            System.out.println("Empty directory ..Exiting the client");
 
            System.exit(0);
 
        }
 
 
 
        for (int i = 0; i < fileCount; i++) {
 
            System.out.println("Sending " + files[i].getAbsolutePath());
 
            sendFile(files[i].getAbsolutePath(), fileCount - i - 1);
 
            System.out.println(files[i].getAbsolutePath());
 
        }
 
    }
 
 
 
    public void sendFile(String fileName, int index) {
 
        fileEvent = new FileEvent();
 
        fileEvent.setDestinationDirectory(destinationDirectory);
 
        fileEvent.setSourceDirectory(sourceDirectory);
 
        File file = new File(fileName);
 
        fileEvent.setFilename(file.getName());
 
        fileEvent.setRemainder(index);
 
        DataInputStream diStream = null;
 
        try {
 
            diStream = new DataInputStream(new FileInputStream(file));
 
            long len = (int) file.length();
 
            byte[] fileBytes = new byte[(int) len];
 
 
 
            int read = 0;
 
            int numRead = 0;
 
            while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
 
                    fileBytes.length - read)) >= 0) {
 
                read = read + numRead;
 
            }
 
            fileEvent.setFileData(fileBytes);
 
            fileEvent.setStatus("Success");
 
        } catch (Exception e) {
 
            e.printStackTrace();
 
            fileEvent.setStatus("Error");
 
 
 
        }
 
 
 
        try {
 
            outputStream.writeObject(fileEvent);
 
        } catch (IOException e) {
 
            e.printStackTrace();
 
        }
 
    }
 
 
 
    public static void main(String[] args) {
 
        Client client = new Client();
 
        client.connect();
 
        client.locateFiles();
 
    }
 
}

pour le serveur :
import java.net.ServerSocket;
 
import java.net.Socket;
 
import java.io.File;
 
import java.io.FileOutputStream;
 
import java.io.IOException;
 
import java.io.ObjectInputStream;
 
 
 
public class Server {
 
    private ServerSocket serverSocket = null;
 
    private Socket socket = null;
 
    private ObjectInputStream inputStream = null;
 
    private FileEvent fileEvent;
 
    private File dstFile = null;
 
    private FileOutputStream fileOutputStream = null;
 
 
 
    public Server() {
 
 

    }
 
 
 
    /**


* Accepts socket connection

*/
 
    public void doConnect() {
 
        try {
 
            serverSocket = new ServerSocket(4445);

            socket = serverSocket.accept(); 
            inputStream = new ObjectInputStream(socket.getInputStream());
 
        } catch (IOException e) {
 
            e.printStackTrace();
 
        }
 
    }
 
 
 
    /**


* Reading the FileEvent object and copying the file to disk.

*/
 
    public void downloadFiles() {
 
        while (socket.isConnected()) {
 
            try { 
                fileEvent = (FileEvent) inputStream.readObject();

                if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
 
                    System.out.println("Error occurred ..with  file" + fileEvent.getFilename() + "at sending end .."); 
 

                }
 
                String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();

                if (!new File(fileEvent.getDestinationDirectory()).exists()) {
 
                    new File(fileEvent.getDestinationDirectory()).mkdirs();
 
                }
 
                dstFile = new File(outputFile);
 
                fileOutputStream = new FileOutputStream(dstFile);
 
                fileOutputStream.write(fileEvent.getFileData());
 
                fileOutputStream.flush();
 
                fileOutputStream.close(); 
                System.out.println("Output file : " + outputFile + " is successfully saved ");

                if (fileEvent.getRemainder() == 0) {
 
                    System.out.println("Whole directory is copied...So system is going to exit");
 
                    System.exit(0);
 
                }
 
 
 
            } catch (IOException e) {
 
                e.printStackTrace();
 
            } catch (ClassNotFoundException e) {
 
                e.printStackTrace();
 
            }
 
        }

    }
 
    public static void main(String[] args) {
 
        Server server = new Server();
 
        server.doConnect();
 
        server.downloadFiles();
 
    }

}

et la derniere classe :
import java.io.Serializable;
 
 
 
public class FileEvent implements Serializable {
 
 
    public FileEvent() {
 
    }
 

    private static final long serialVersionUID = 1L; 
 
 
    private String destinationDirectory;

    private String sourceDirectory;

    private String filename;

    private long fileSize;
    
    private byte[] fileData;
 
    private String status;
 
    private int remainder;
 
 
 
    public String getDestinationDirectory() {
 
        return destinationDirectory;
 
    }
 
 
 
    public void setDestinationDirectory(String destinationDirectory) {
 
        this.destinationDirectory = destinationDirectory;
 
    }
 
 
 
    public String getSourceDirectory() {
 
        return sourceDirectory;
 
    } 
 

    public void setSourceDirectory(String sourceDirectory) {
 
        this.sourceDirectory = sourceDirectory;
 
    }
 
 
 
    public String getFilename() {
 
        return filename;
 
    }
 
 
 
    public void setFilename(String filename) {
 
        this.filename = filename;
 
    }
 
 
 
    public long getFileSize() {
 
        return fileSize;
 
    }
 
  
    public void setFileSize(long fileSize) {
 
        this.fileSize = fileSize;
 
    }
 
  
    public String getStatus() {
 
        return status;
 
    }
 
 
 
    public void setStatus(String status) {
 
        this.status = status;
 
    }
 
 
 
    public byte[] getFileData() {
 
        return fileData;
 
    }
 
 
 
    public void setFileData(byte[] fileData) {
 
        this.fileData = fileData;
 
    }
 
 
 
    public int getRemainder() {
 
        return remainder;
 
    }
 
 
 
    public void setRemainder(int remainder) {
 
        this.remainder = remainder;
 
    }
 
}

Mais il m'affiche cette erreur je comprends pas pourquoi :
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at test2.Server.downloadFiles(Server.java:42)
at test2.Server.main(Server.java:72)

svp si vous pouvez m'aider ..


EDIT: Ajout des balises code.
Afficher la suite 

Votre réponse

1 réponse

Messages postés
5300
Date d'inscription
dimanche 4 mai 2003
Statut
Modérateur
Dernière intervention
10 décembre 2018
0
Merci
Salut,

Si le serveur reçoit une exception de type "Connection reset", c'est qu'il est probablement en train de lire sur une connexion qui a déjà été fermée par l'autre extrémité.

- Ton fichier est quand même lu correctement coté serveur: ignore l'exception.
- Ton fichier n'est pas lu correctement: debug l'application.

Pour rappel (source) Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket (see isClosed()) if it was successfuly connected prior to being closed.

Commenter la réponse de Twinuts

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.