Transferindo Arquivos por Socket

5 respostas
R

Olá

To tentando fazer uma aplicação transferir arquivos mas to tendo um problema.

package meuservidor;

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

class TheServer extends Thread {
    
    private Socket s;
    private BufferedReader in;
    private byte data[] = new byte[1024];
    
    public TheServer(Socket socket) throws IOException {
        s = socket;
        in = new BufferedReader(
                new InputStreamReader(
                    socket.getInputStream()));                
        start();
    }
    
    public void run() {
        try {
            while (true) {
                String str = in.readLine();
                                
                if (str.equals("END")) break;
                                
                if (str.equals("FILES")) {
                    PrintWriter out = new PrintWriter(
                        new BufferedWriter(
                            new OutputStreamWriter(
                                s.getOutputStream())), true);
                    out.println(this.getArquivos());                    
                } else {
                    
                    
                    if (str.substring(0, 8).equals("TRANSFER")) {
                        FileInputStream fileIn = new FileInputStream(str.substring(9));                    
                        OutputStream out = s.getOutputStream();
                        
                        int size;
                        while ((size = fileIn.read(data)) != -1)
                        {
                            out.write(data, 0, size);
                            out.flush();
                        }                        
                        out.close();
                        fileIn.close();
                    }
                }
            }                

            System.out.println("closing...");
       } catch(IOException e) {
           e.printStackTrace();
           System.err.println("IO Exception");
       } finally {
           try {
               s.close();
           } catch(IOException e) {
               System.err.println("Socket not closed");
           }
       }    
    }
    
    public String getArquivos() {
        File dir = new File(System.getProperty("user.dir"));
        File[] files = dir.listFiles();
        StringBuilder lista = new StringBuilder();
        
        for (int i = 0; i &lt files.length; i++) {
            if (files[i].isFile()) {
                lista.append(files[i].getName());
                lista.append("|");
            }
        }
        return lista.toString();
    }
}
    
public class FileServer {
    static final int PORT = 2424;

    public static void main(String[] args) throws IOException {
        ServerSocket s = new ServerSocket(PORT);
        System.out.println("Server Started");
        try {
            while(true) {
                // Blocks until a connection occurs:
                Socket socket = s.accept();
                try {
                    new TheServer(socket);
                } catch(IOException e) {
                    socket.close();
                }
            }
        } finally {
            s.close();
        }
    }
}
package meucliente;

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

public class FileClient {
    
    private Socket s;
    private byte data[] = new byte[1024];
    private PrintWriter out;

    public FileClient() {
    }
    
    public void desconectar() throws IOException {        
        out.println("END");
        s.close();
    }
    
    public String conectar(String ip, int porta) throws IOException {
        s = new Socket(ip, porta);
        
        out = new PrintWriter(
                new BufferedWriter(
                    new OutputStreamWriter(
                        s.getOutputStream())), true);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                    s.getInputStream()));  
        
        out.println("FILES");        
        
        String str = in.readLine();
        return str;
    }
    
    public void download(String arquivo) throws IOException {
        InputStream in = s.getInputStream();
        
        out.println("TRANSFER|" + arquivo);
        
        FileOutputStream fileOut = new FileOutputStream(arquivo);
        
        int size;
        while ((size = in.read(data)) != -1)
        {
            fileOut.write(data, 0, size);
            fileOut.flush();
        }
        fileOut.close();
    }
}

Quando chamo o método download da classe FileClient eu até recebo o arquivo, mas a classe TheServer dispara a seguinte Exception:

java.net.SocketException: socket closed
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.read(SocketInputStream.java:129)
        at sun.nio.cs.StreamDecoder$CharsetSD.readBytes(StreamDecoder.java:411)
        at sun.nio.cs.StreamDecoder$CharsetSD.implRead(StreamDecoder.java:453)
        at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:183)
        at java.io.InputStreamReader.read(InputStreamReader.java:167)
        at java.io.BufferedReader.fill(BufferedReader.java:136)
        at java.io.BufferedReader.readLine(BufferedReader.java:299)
        at java.io.BufferedReader.readLine(BufferedReader.java:362)
        at meuservidor.TheServer.run(FileServer.java:32)
IO Exception

Alguém sabe o por que?

Valeu

5 Respostas

S

O seu programa tenta usar ou fechar uma conexão que já foi fechada.

[]´s

R

Sabendo que esse erro acontece no método run() da classe TheServer, onde o socket está sendo fechado de forma incorreta?

T

Muitas vezes você precisa usar algum método específico da classe Socket, como “shutdown”.

R

Algo de errado pode estar acontecendo com este trecho?

...
if (str.substring(0, 8).equals("TRANSFER")) {
           FileInputStream fileIn = new FileInputStream(str.substring(9));                    
           OutputStream out = s.getOutputStream();
                         
           int size;
           while ((size = fileIn.read(data)) != -1)
           {
                    out.write(data, 0, size);
                    out.flush();
           }                        
           out.close();
           fileIn.close();
}
...
Blackstorm

Não será por que você está utilizando o OutputStream para receber o arquivo?Pelo que vi você está realizando os teste localmente e pode acabar passando despercebido disto.
Ao invés de colocar out.write(); coloque in.read com in sendo o InputStream.

Valeu

Criado 11 de setembro de 2006
Ultima resposta 27 de out. de 2006
Respostas 5
Participantes 4