PDA

View Full Version : [java] trasferimento file server-client


lauura
13-09-2006, 17:15
in breve.. devo implementare dei comandi dove mi serve che un file venga copiato da server a client per poi esser letto o modificato da quest' ultimo.
ho provato ad usare sia la classe BufferedInputStream che la classe DataInputStream ma con scarsi risultati nel senso che a volte mi trasferisce il file ma non tutto (quindi se è un immagine non viene visualizzata) oppure mi crea semplicemente un file vuoto.. ho provato in mille modi..

LATO SERVER:
BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream());
FileInputStream in = new FileInputStream(clientFile.getAbsolutePath());
byte buffer[] = new byte[1];
System.out.println( "Invio file in corso..." );
int i;
while((i = in.read(buffer,0,buffer.length)) != -1){
out.write(buffer,0,i);
}
out.flush();
out.close();
System.out.println( "Invio completato." );

LATO CLIENT:

System.out.println("Ricezione file in corso..");
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
FileOutputStream out = new FileOutputStream(lDir + fileName);
byte buffer[] = new byte[1];
int i;
while ((i = in.read(buffer,0,buffer.length)) != -1){
out.write(buffer,0,i);
}
out.flush();
out.close();
in.close();
System.out.println( "Ricezione completata!" );


se però chiudo il socket dopo aver trasferito il file allora il file viene creato correttamente ma ovviamente mi serve che il socket rimanga aperto...
HELP!!grassie

lauura
14-09-2006, 11:15
Aiuto???

lauura
14-09-2006, 14:18
HELP!!grassie

TempestaT400
18-09-2006, 03:00
Ma usi le classi DatagramSocket e DatagramPacket???

per le connessioni ho usato le classi Datagram

Lato Client



import java.io.*;
import java.net.*;


public class LineClient {

public static void main(String[] args) throws IOException {
// creazione della socket datagram

DatagramSocket socket = new DatagramSocket();
System.out.println("LineClient: started");
System.out.println("Socket: "+ socket);
// creazione e invio del pacchetto di richiesta
byte[] buf = new byte[256];
InetAddress addr;
if (args.length == 0)
addr = InetAddress.getByName(null);
else
addr = InetAddress.getByName(args[0]);
PrintWriter out = new PrintWriter(new FileWriter("ric.txt"), true);

while(true){
//invio richiesta
DatagramPacket packet = new DatagramPacket(buf, buf.length, addr, 4444);
socket.send(packet);
System.out.println("Request sent to "+ addr);

// pulizia del buffer
for (int j=0; j<256; j++)
buf[j]=' ';
// ricezione e stampa della risposta
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// sospensiva solo per i millisecondi indicati, dopodichè solleva una SocketException
String received = new String(packet.getData());
if(received.trim().equals("null"))
break;
else
out.println(received.trim());
}
System.out.println("LineClient: closing...");
socket.close();
}
}


Lato Server



import java.io.*;
import java.net.*;
import java.util.*;

public class LineServer {
public static final int PORT = 4444; // porta al difuori del range 1-1024 !
public static final String FILE = "file.txt";
DatagramSocket socket;
static BufferedReader in = null;
static boolean moreLines = true;

public LineServer(){
try {
// creazione della socket datagram
socket = new DatagramSocket(PORT);
System.out.println("Socket: " + socket);
} catch (SocketException e) {System.err.println("Unable to create the socket");}
try {
// associazione di uno stream
// di input al file da cui estrarre le linee
in = new BufferedReader(new FileReader(FILE));
System.out.println("File "+FILE+" opened");
} catch (FileNotFoundException e)
{
System.err.println("Could not open");
}
}

public static void main(String[] args) throws IOException {
System.out.println("LineServer: started");
LineServer server=new LineServer();
while (moreLines) {
try {
byte[] buf = new byte[256];
// ricezione della richiesta
DatagramPacket packet = new DatagramPacket(buf, buf.length);
server.socket.receive(packet);
// preparazione della linea da inviare
String dString = null;
if (in == null)
dString = new Date().toString();
else
dString = getNextLine();

if (dString!=null) {
buf = dString.getBytes();
// "impacchettamento" e invio della risposta
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
server.socket.send(packet);
System.out.println("Sending packet to "+address+", "+port);
}
else{
buf = "null".getBytes();
// "impacchettamento" e invio della risposta
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
server.socket.send(packet);
}
} catch (IOException e) {
e.printStackTrace();
moreLines = false;
}
}

System.out.println("No more lines. Goodbye.");
System.out.println("LineServer: closing...");
server.socket.close();
}

static String getNextLine() {
String returnValue = null;
try {
if ((returnValue = in.readLine()) == null) {
in.close();
moreLines = false;
returnValue = null;
//returnValue = "No more lines. Goodbye.";
}
} catch (IOException e) {
returnValue = "IOException occurred.";
}
return returnValue;
}
}

lauura
18-09-2006, 16:40
mi dispiace ma ho bisogno di un trsferimento tcp e non udp..
ho provato ad utilizzare le classi datainputstream e dataoutputstream che tutto sommato il trasferimento me lo fa l unico grosso problema e' che mi chiude la connessione dopo il trasferimento cosa che assolutamente non mi deve fare..
SERVER
DataOutputStream out = new DataOutputStream(client.getOutputStream());
DataInputStream in = new DataInputStream(new FileInputStream(clientFile.getAbsolutePath()));
byte buffer[] = new byte[1024];
System.out.println( "Invio file in corso..." );
int i;
while((i = in.read(buffer,0,buffer.length)) != -1){
System.out.println("ci sono");
out.write(buffer,0,i);
out.flush();
}
out.flush();
out.close();
in.close();
System.out.println( "Invio completato." );
addToLogFileList("Invio file '"+clientFile.getName()+"' in lettura effettuato.");

CLIENT
System.out.println("Ricezione file in corso..");
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(new FileOutputStream(lDir + fileName));
byte buffer[] = new byte[1024];
int i;
while ((i = in.read(buffer,0,buffer.length)) != -1){
System.out.println("ci sono");
out.write(buffer,0,i);
out.flush();
}
out.flush();
out.close();
in.close();
System.out.println( "Ricezione completata!" );

TempestaT400
18-09-2006, 19:35
Appena ho un pò di tempo trasformo questa classe da UDP a TCP, anche se non è un lavoro poi così complicato!!!

TempestaT400
19-09-2006, 01:21
Ho appena postato il codice modificato per le connessioni TCP in questo post.!.

http://www.hwupgrade.it/forum/showthread.php?p=13881078#post13881078

Cmq, per far si che la connessione non venga chiusa alla fine dell'invio del file basta solamente far gestire ad una classe Thread separata l'invio del file, mentre la classe server principale ritorna nel loop di attesa!!!

esempio...



public class MultiServer {
public static void main(String [] args)throws IOException{
ServerSocket server = new ServerSocket(1050);
System.out.println("MultiServer: started");

try{
while(true){
Socket clientSocket = server.accept();
System.out.println("Connection Accepted: "+clientSocket);
try{
new ServerThread(clientSocket);
}catch(IOException ioe){
clientSocket.close();
}
}
}catch(IOException ioe){
System.err.println("Accept failed!");
System.exit(1);
}
System.out.println("MultiServer: closing...");
server.close();
}
}



più chiaro di così, non so cosa fare!!!!