codice:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
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 TFTP_Client {
DatagramSocket dataSocket;
DatagramPacket dataPacket;
String nome;
long dimensione;
private InetAddress indirizzoServer;
private int porta;
public void Start() throws IOException {
porta = 9876;
indirizzoServer = InetAddress.getByName("127.0.0.1");
JFileChooser fileChooser = new JFileChooser();
int n = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
String path_file = file.getAbsolutePath();
nome = file.getName();
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);
invia_Nome(nome);
invia_File(file, nome );
}
private void invia_File(File file, String nome) throws IOException {
System.out.println("*** Inizio invio file");
try {
dataSocket = new DatagramSocket();
byte[] buf = new byte[1024];
int read,tot=0;
FileInputStream inputStream = new FileInputStream(file);
dataPacket = new DatagramPacket (buf, buf.length, indirizzoServer, porta);
// INVIO I PACCHETTI
while ((read = inputStream.read(buf)) != -1 ){
tot += read;
System.out.println(" - "+tot+ " byte");
dataSocket.send(dataPacket);
}
System.out.println("*** FILE INVIATO CON SUCCESSO ***");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} // FINE INVIA_FILE
private void invia_Nome(String nome) throws IOException {
dataSocket = new DatagramSocket();
String nome_file = nome;
System.out.println("Il nome del file è: " +nome_file);
byte [] name = {0};
name = nome_file.getBytes();
dataPacket = new DatagramPacket (name, name.length, indirizzoServer, porta);
dataPacket.setData(name);
dataPacket.setLength(name.length);
// INVIO DEL PACCEHTTO SUL SOCKET
dataSocket.send(dataPacket);
}// FINE INVIA NOME
public static void main(String[] args) throws IOException
{
TFTP_Client tftpClient = new TFTP_Client();
tftpClient.Start();
}
}