Questo è il codice che ho usato in un esercizio all'università... E' stato in gran parte copiato da un sito... magari può esserti di aiuto:
server:
codice:
public class FileServer {
public static void main (String [] args ) throws IOException {
String desktopPath = System.getProperty("user.home") + "/Desktop";
File myFile = new File(desktopPath+"/immagine.bmp");
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// sendfile
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectOutputStream os = new ObjectOutputStream(sock.getOutputStream());
os.writeInt(mybytearray.length);
bis.read(mybytearray,0,mybytearray.length);
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}
client:
codice:
public class FileClient{
public static void main (String [] args ) throws IOException {
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket("127.0.0.1",13267);
System.out.println("Connecting...");
// receive file
ObjectInputStream is = new ObjectInputStream(sock.getInputStream());
int dimension=is.readInt();
byte [] mybytearray = new byte [dimension];
System.out.println("Dimensione="+dimension);
FileOutputStream fos = new FileOutputStream("immagine.bmp");
BufferedOutputStream bos = new BufferedOutputStream(fos);
// thanks to A. Cádiz for the bug fix
do {
bytesRead =is.read(mybytearray, current, (mybytearray.length-current));
current += bytesRead;
} while(current<dimension);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
}