Magazine Informatica

Trasferimento file in Java

Creato il 20 maggio 2012 da Ketek @CarloVentrella

Oggi vi propongo una coppia di programmi scritti in Java che ci permette di trasferire i file tra pc via socket attraverso l''architettura client/server. Il funzionamento è molto semplice:

  • Connessione tra server e client nella porta predefinita( ex. 9999);
  • Il server invia al client i parametri del file che sta per inviare;
  • Il client riceve i parametri e si prepara per la ricezione del file;
  • Il server invia il file al client.

Vediamo subito i due codici:

SERVER:

 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
 
public class send
{
                ServerSocket ss;
                Socket s;
                public send() throws IOException
                {
                               int port = 9999;
                               String path_file = "C:\\prova.xtx";
                               int dim_file = 481;
                               String nome = "prova.xtx";
                               // mi connetto al client
 
                               s = connect(port);
 
                               // invio il file
                               send_File(path_file,nome,dim_file);
                }
 
                // funzione per connettermi al client
                public Socket connect(int port)
                {
                               Socket sock = null;
                               try {
                                               ss = new ServerSocket(9999);
                                               System.out.println("* Attendo un client");
                                               sock = ss.accept();
 
                               } catch (UnknownHostException e) {
                                               e.printStackTrace();
                               } catch (IOException e) {
                                               e.printStackTrace();
                               }
                               System.out.println("* connesso con successo");
                               return sock;
                }
 
                public void invia_parametri(String nome,int dimensione,ObjectOutputStream oos)
                {
                               String param = nome+","+dimensione;
                               try {
                                               oos.flush();
                                               oos.writeObject(param);
                               } catch (IOException e) {
                                               e.printStackTrace();
                               }
                }
 
                public void send_File(String path_file,String nome,int dim_file) throws IOException
                {
                               System.out.println("* Inizio processo di invio del file");
                               String path = path_file;
                               int dim = dim_file;
                               FileInputStream fis = null;
                               ObjectOutputStream oos;
 
                               try {
 
                                               fis = new FileInputStream(path);
                                               oos = new ObjectOutputStream(s.getOutputStream());
 
                                               byte[] buf = new byte[1024];
 
                        int read,tot=0;
 
                        // invio i dati del file al client
                        invia_parametri(nome,dim,oos);
                        // inizio fase di lettura
 
                        System.out.println("* Inviati: ");
                        oos.flush();
 
            while ((read = fis.read(buf)) != -1 ) {
 
             tot += read;
             System.out.println("  - "+tot+ " byte");
             oos.write(buf, 0, read);
             oos.flush();
 
            }
 
            System.out.println("** File inviato con successo");
 
                               } catch (FileNotFoundException e) {
                                               e.printStackTrace();
                               }
                }
                public static void main(String Args[]) throws IOException
                {
                               new send();
                }
 
}
 

CLIENT:

 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.net.UnknownHostException;
 
public class get
{
                Socket s;
                public get() throws IOException
                {
                               String ip = "127.0.0.1";
                               int port = 9999;
                               String default_dir = "C:\\Users\\CARLO\\Desktop\\";
                               // mi connetto al server
                               boolean connected = connect(ip,port);
                               if (connected == false)
                               {
                                               System.out.println("Non esiste alcun server sulla porta " + port);
                                               System.exit(0);
                               }
                               // avvio la ricezione del file
                               get_File(default_dir);
                }
                // funzione per connettermi al server
                public boolean connect(String ip,int port)
                {
                               boolean result = false;
                               try {
                                               s = new Socket(ip,port);
                                               result = true;
                                               System.out.println("* connesso con successo");
                               } catch (UnknownHostException e) {
                                               e.printStackTrace();
                               } catch (IOException e) {
                                               e.printStackTrace();
                               }
 
                               return result;
                }
                public String[] ottengo_parametri(ObjectInputStream ois)
                {
                               String parametri_file[] = null;
                               try {
                                               String param = (String)ois.readObject();
                                               parametri_file = param.split(",");
                               } catch (IOException e) {
                                               e.printStackTrace();
                               } catch (ClassNotFoundException e) {
                                               e.printStackTrace();
                               }
                               return parametri_file;
                }
 
                public void get_File(String dest) throws IOException
                {
                               System.out.println("* Inizio processo di ricezione");
 
                               String destinazione = dest;
                               int read,tot = 0;
                               ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
 
        String [] param_file = ottengo_parametri(ois);
        String nome = param_file[0];
        int dimensione = Integer.parseInt(param_file[1]);
 
        // stream per il salvataggio del file su disco
        File file = new File(destinazione+nome);
        // apro outputStream
        FileOutputStream fos = new FileOutputStream(file, true);
 
        byte[] buf = new byte[1024];
 
        System.out.println("* Ricevo: ");
 
        // prendo il pacchetto di 1024 kb
 
        try{
        while ((read = ois.read(buf)) != -1) {
        tot += read;
        System.out.println("  - "+tot+ " byte");
        // scrivo il pacchetto su disco
        fos.write(buf, 0, read);
        }
 
        }catch(java.net.SocketException e)
        {
                if (tot == dimensione)
                {
                               System.out.println("** File ricevuto con successo");
                }
                else
                {
                               System.out.println("$$ ERRORE - c''è stato qualche problema!");
                }
        }
                }
                public static void main(String Args[]) throws IOException
                {
                  new get();
                }
}
 


Potrebbero interessarti anche :

Ritornare alla prima pagina di Logo Paperblog

Possono interessarti anche questi articoli :

Dossier Paperblog