Boa tarde,
Estou usando socket para fazer transferência de arquivo entre cliente/servidor.. Eu consigo pegar o arquivo do servidor para o cliente, mas não consigo mandar o arquivo do cliente para o servidor. O código que eu estou usando está abaixo:
public void cliente(String fName) throws FileNotFoundException, UnknownHostException, IOException {
File f = new File("/home/andre/" + fName);
FileInputStream in = new FileInputStream(f);
Socket socket = new Socket("localhost", 5678);
OutputStream out = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(out);
BufferedWriter writer = new BufferedWriter(osw);
writer.write(f.getName() + "\n");
writer.flush();
int tamanho = 4096; // buffer de 4KB
byte[] buffer = new byte[tamanho];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
Agora abaixo eu crio o arquivo que eu quero enviar para o servidor:
public void salvarOriginal() throws IOException {
File arquivo_cache = new File(arquivo_server);
String hello = texto.getText();
FileWriter fw = new FileWriter(pasta_principal.toString() + "/" + arquivo_cache);
fw.write(hello);
fw.close();
}
E o meu servidor está assim:
public class Server extends Thread {
protected Socket s;
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5678);
System.out.println("Capivara Server [start]");
while (true) {
Socket cliente = ss.accept();
Server c = new Server(cliente);
c.start();
}
}
public Server(Socket s) {
System.out.println("New client in Capivara!");
this.s = s;
}
public void run() {
OutputStream out = null;
InputStream in = null;
File arquivo = null;
try {
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String caminho = input.readLine();
arquivo = new File(caminho);
in = new FileInputStream(arquivo);
out = s.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
System.out.println("Transfer File " + arquivo + " success!");
s.close();
} catch (IOException e) {
} finally {
try {
in.close();
} catch (IOException ex) {
}
}
}
}
Obrigado.