ho un server socket che rimane connesso e accetta file in entrata:
codice:
public class Server {
private final int PORT = port;
public static void main(String[] args) {
Server s = new Server();
s.listen();
}
private void listen() {
try {
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Sono sulla " + ss);
for (;;) {
Socket s = ss.accept();
System.out.println("Conessione da " + s);
new MTManager(s).run();
Thread.sleep(100);
}
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
dove MTManager server per gestire i thread e il salvataggio:
codice:
public class MTManager implements Runnable {
private final String DIR_SAVE = "/media/hd/ftp";
private Socket socket;
public MTManager(Socket socket) {
this.socket = socket;
}
public void run() {
try {
System.out.println("Presa in carico nuova connessione da " + socket);
ObjectInputStream oin = new ObjectInputStream(socket.getInputStream());
File inFile = (File) oin.readObject();
File saveFile = new File(DIR_SAVE + "/" + inFile.getName());
save(inFile, saveFile);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
socket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
private void save(File in, File out) throws IOException {
System.out.println(" --ricezione file " + in.getName());
System.out.println(" --dimensione file " + in.length());
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out, true);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
System.out.println(" --ricezione completata");
OperationsFile.createLog("Nome file: " + in.getName() + "\nDimensione file: " + in.length());
}
}
il client è:
codice:
public class Client {
private final String HOST = "host";
private final int PORT = port;
public static void main(String[] args) {
Client c = new Client();
c.sendFile();
}
private void sendFile() {
Socket socket = null;
File file = new File(System.getProperty("user.home") + "/booklog.log");
try {
socket = new Socket(HOST, PORT);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.reset();
oos.writeObject(file);
oos.flush();
oos.close();
} catch (UnknownHostException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
ora, se sia il client che il server risiedono sulla stessa macchina funziona tutto.
se invece il server è su un altro pc allora riesco a connettermi ma nn ad inviare i file in quanto mi dice che prende il file da una directory che nn esiste (in questo caso la home del mac in ufficio).
come posso fare??