简体   繁体   中英

Java Socket MultiThread File Transfer

I have a problem in my code. I do not know how to solve. I need to send a file, and then download the same. What happens is that I can send multiple files, but if I download only one, I can not send anything. Because the socket is closed. I'm racking my brain and I could not solve. Does anyone have any tips? Thank you.

Server.java

public class Server {

    private static ServerSocket serverSocket;
    private static Socket clientSocket = null;

    public static void main(String[] args) throws IOException {

        try {
            serverSocket = new ServerSocket(4444);
            System.out.println("Server started.");
        } catch (Exception e) {
            System.err.println("Port in use.");
            System.exit(1);
        }

        while (true) {
            try {
                clientSocket = serverSocket.accept();
                System.out.println("Conection Accept : " + clientSocket);

                Thread t = new Thread(new ClientConnection(clientSocket));

                t.start();

            } catch (Exception e) {
                System.err.println("Conection Error.");
            }
        }
    }
}

ClientConnection.java

public class ClientConnection implements Runnable {

    private Socket clientSocket;
    private BufferedReader in = null;

    public ClientConnection(Socket client) {
        this.clientSocket = client;
    }

    @Override
    public void run() {
        boolean done = false;
        try{
            in = new BufferedReader(new InputStreamReader(
                    clientSocket.getInputStream()));

        }
        catch(Exception e){}

        String clientSelection;

        while (!done) {

            try {


                clientSelection = "";

                while ((clientSelection = in.readLine()) != null) {
                    switch (clientSelection) {
                    case "send":
                        receiveFile();
                        break;
                    case "get":
                        String outGoingFileName;
                        while ((outGoingFileName = in.readLine()) != null) {
                            sendFile(outGoingFileName);
                        }
                        break;
                    default:
                        System.out.println("Wrong Command...");
                        break;
                    }
                }

            } catch (IOException ex) {
                System.err.println("Erro--" + ex);
            }
        }
    }

    public void receiveFile() {
        try {
            int bytesRead;

            DataInputStream clientData = new DataInputStream(
                    clientSocket.getInputStream());

            String fileName = clientData.readUTF();
            OutputStream output = new FileOutputStream(
                    ("received_from_client_" + fileName));
            long size = clientData.readLong();
            byte[] buffer = new byte[1024];
            while (size > 0
                    && (bytesRead = clientData.read(buffer, 0,
                            (int) Math.min(buffer.length, size))) != -1) {
                output.write(buffer, 0, bytesRead);
                size -= bytesRead;
            }
            output.flush();
            output.close();

            System.out.println("File " + fileName + " received from client.");

        } catch (IOException ex) {
            System.err.println("Error." + ex);
        }
    }

    public void sendFile(String fileName) {
        try {

            File myFile = new File(fileName);
            byte[] mybytearray = new byte[(int) myFile.length()];

            FileInputStream fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);

            DataInputStream dis = new DataInputStream(bis);
            dis.readFully(mybytearray, 0, mybytearray.length);

            OutputStream os = clientSocket.getOutputStream();

            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(myFile.getName());
            dos.writeLong(mybytearray.length);
            dos.write(mybytearray, 0, mybytearray.length);
            dos.flush();

            System.out.println("File " + fileName + " send to client.");

        } catch (Exception e) {
            System.err.println("Error! " + e);
        }
    }
}

Client.java

public class Client {

    private static Socket sock;
    private static String fileName;
    private static String newName;
    private static BufferedReader bufferReader;
    private static PrintStream os;


    public static void main(String[] args) throws IOException {
        try {
            sock = new Socket("localhost", 4444);
            bufferReader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            System.err.println("Error - Try again.");
            System.exit(1);
        }

        os = new PrintStream(sock.getOutputStream());

        boolean done = false;

        while (!done) {
            try {

                switch (selectAction()) {
                case "send":
                    os.println("send");
                    sendFile();
                    break;
                case "get":
                    os.println("get");
                    System.err.print("File Name: ");
                    fileName = bufferReader.readLine();
                    os.println(fileName);
                    receiveFile(fileName);
                    break;
                case "exit":
                    done = true;
                    os.println("exit");
                    System.out.println("Connection closed");
                    break;
                }
            } catch (Exception e) {
                System.err.println("Wrong command");
            }
        }

        sock.close();
    }

    public static String selectAction() throws IOException {
        System.out.println("");
        System.out.println("send - Send File.");
        System.out.println("get - Get File.");
        System.out.println("exit - Exit.");
        System.out.print("\nSelect one Option: ");

        return bufferReader.readLine();
    }

    public static void sendFile() {
        try {
            System.err.print("File Name: ");
            fileName = bufferReader.readLine();

            File myFile = new File(fileName);
            byte[] mybytearray = new byte[(int) myFile.length()];

            FileInputStream fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);

            DataInputStream dis = new DataInputStream(bis);
            dis.readFully(mybytearray, 0, mybytearray.length);

            OutputStream os = sock.getOutputStream();

            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(myFile.getName());
            dos.writeLong(mybytearray.length);
            dos.write(mybytearray, 0, mybytearray.length);
            dos.flush();


            System.out.println("File " + fileName
                    + " send to server.");
        } catch (Exception e) {
            System.err.println("ERROR! " + e);
        }
    }

    public static void receiveFile(String fileName) {
        try {
            int bytesRead;
            InputStream in = sock.getInputStream();

            DataInputStream clientData = new DataInputStream(in);

            fileName = clientData.readUTF();
            OutputStream output = new FileOutputStream(
                    ("received_from_server_" + fileName));
            long size = clientData.readLong();
            byte[] buffer = new byte[1024];
            while (size > 0
                    && (bytesRead = clientData.read(buffer, 0,
                            (int) Math.min(buffer.length, size))) != -1) {
                output.write(buffer, 0, bytesRead);
                size -= bytesRead;
            }
            output.flush();

            System.out
                    .println("File " + fileName + " received from Server.");
        } catch (IOException ex) {
            Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE,
                    null, ex);
        }
    }
}

Thanks.

After much tinkering. I found a way to solve.

One "While" that ended up polluting a variable. At least that's what I identified.

in my Case (ClientConnection.java)

case "get":
        String outGoingFileName;
        while ((outGoingFileName = in.readLine()) != null) {
            sendFile(outGoingFileName);
        }
break;

Solved the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM