codice:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JFileChooser;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author ste
*/
public class Client_Socket {
Socket socket;
public Client_Socket() throws IOException{
String indirizzoServer = "192.168.1.234";
int porta = 9876;
JFileChooser fileChooser = new JFileChooser();
int n = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
String path_file = file.getAbsolutePath();
String nome = file.getName();
long dimensione = file.length();
System.out.println("Il nome del fileselezionato è: " +nome);
System.out.println("La sua dimensione : " +dimensione+ " byte");
System.out.println("Percorso: " +path_file);
boolean connesso = connect(indirizzoServer,porta);
if (connesso == false)
{
System.out.println("*** ATTENZIONE: Non esiste alcun server sulla porta ***" + porta);
System.exit(0);
}
// avvio la ricezione del file
invia_File(file, nome, dimensione);
}
/**************************************************************************/
public boolean connect(String ip,int porta)
{
boolean result = false;
try {
socket = new Socket(ip,porta);
result = true;
System.out.println("*** CONNESSO CON SUCCESSO *** ");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**************************************************************************/
public void invia_File(File file, String nome,long dimensione) throws IOException
{
System.out.println("*** Inizio invio file");
String name = nome;
long dimension = dimensione;
FileInputStream fis = null;
DataOutputStream oos;
try{
fis = new FileInputStream(file);
oos = new DataOutputStream(socket.getOutputStream());
byte[] buf = new byte[1024];
int read,tot=0;
// invio i dati del file al client
invia_nome(nome, oos);
invia_dimensione(dimensione, oos);
System.out.println("iNVIATI: ");
oos.flush();
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 void invia_nome(String nome, DataOutputStream oos){
try {
oos.flush();
oos.writeUTF(nome);
//oos.writeLong(dimensione);
} catch (IOException e) {
e.printStackTrace();
}
}
public void invia_dimensione(long dimensione, DataOutputStream oos){
try {
oos.flush();
oos.writeLong(dimensione);
} catch (IOException e) {
e.printStackTrace();
}
}
/**************************************************************************/
public static void main(String[] args) throws IOException {
new Client_Socket();
}
}